オブジェクトの配列を取り込んで、上記のJSONをJavaScriptのツリー構造に変換します
このようなオブジェクトの配列があるとします-
const arr = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
]; そのようなオブジェクトの配列を1つ取り込むJavaScript関数を作成する必要があります。次に、関数は再帰を使用して、上記のJSONをツリー構造に変換する必要があります。
ツリー構造は次のようになります-
nodeStructure: {
text: { name: "root3" },
children: [
{
text: { name: "root2" }
},
{
text: { name: "root1" }
}
]
}
}; 例
このためのコードは-
になりますconst arr = [
{
"parentIndex": '0' ,
"childIndex": '3' ,
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3' ,
"childIndex": '2' ,
"parent": "root3" ,
"child": "root2"
},
{
"parentIndex": '3' ,
"childIndex": '1' ,
"parent": "root3" ,
"child": "root1"
}
];
const partial = (arr = [], condition) => {
const result = [];
for (let i = 0; i < arr.length; i++) {
if(condition(arr[i])){
result.push(arr[i]);
}
}
return result;
}
const findNodes = (parentKey,items) => {
let subItems = partial(items, n => n.parent === parentKey);
const result = [];
for (let i = 0; i < subItems.length; i++) {
let subItem = subItems[i];
let resultItem = {
text: {name:subItem.child}
};
let kids = findNodes(subItem.child , items);
if(kids.length){
resultItem.children = kids;
}
result.push(resultItem);
}
return result;
}
console.log(JSON.stringify(findNodes('ROOT', arr), undefined, 4)); 出力
そして、コンソールの出力は-
になります[
{
"text": {
"name": "root3"
},
"children": [
{
"text": {
"name": "root2"
}
},
{
"text": {
"name": "root1"
}
}
]
}
] -
JavaScript配列をJSONに変換する
JavaScriptで配列をJSONに変換するためのコードは、次のとおりです- 例 <!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>Converting an ar
-
JavaScript-配列オブジェクトの長さ
JavaScriptのlengthプロパティは、オブジェクトのサイズを返します。以下は、文字列および配列オブジェクトの長さのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document