親子関係のあるオブジェクトを生成する
HTML
<ul>
<li><a href="https://teratail.com/questions/84105">JavaScript - javaScriptで親子関係のあるのオブジェクトを作る(84105)|teratail</a></li>
</ul>
JavaScript
'use strict';
(function () {
function getElementById (elementList, id) {
// id = String(id);
for (var i = 0, len = elementList.length, element; i < len; ++i) {
element = elementList[i];
if (element.id === id) {
return element;
}
}
return null;
}
function appendChild (parentObject, childObject) {
Array.isArray(parentObject.children) ? parentObject.children.push(childObject) : parentObject.children = [childObject];
}
var before = [
{
"id": 1,
"parent": 0
},
{
"id": 2,
"parent": 0
},
{
"id": 3,
"parent": 1
},
{
"id": 4,
"parent": 2
},
{
"id": 5,
"parent": 3
}
];
var rootObject = {"id": 0};
before.forEach(function (object, i) {
if (!Array.isArray(object.children)) {
object.children = [];
}
appendChild(object.parent !== 0 ? getElementById(before, object.parent) : rootObject, object);
});
// 期待する整形後のコード
var after = [
{
"id": 1,
"parent": 0,
"children": [
{
"id": 3,
"parent": 1,
"children": [
{
"id": 5,
"parent": 3,
"children": [] // 追加した
}
]
}
]
},
{
"id": 2,
"parent": 0,
"children": [
{
"id": 4,
"parent": 2,
"children": [] // 元々、存在している
}
]
}
];
console.log(JSON.stringify(rootObject.children)); // [{"id":1,"parent":0,"children":[{"id":3,"parent":1,"children":[{"id":5,"parent":3,"children":[]}]}]},{"id":2,"parent":0,"children":[{"id":4,"parent":2,"children":[]}]}]
console.log(JSON.stringify(after)); // [{"id":1,"parent":0,"children":[{"id":3,"parent":1,"children":[{"id":5,"parent":3,"children":[]}]}]},{"id":2,"parent":0,"children":[{"id":4,"parent":2,"children":[]}]}]
console.log(JSON.stringify(rootObject.children) ===...