[英]convert JSON object to JSON tree
var obj = [{
id: 1,
child:[2,4],
data : "hello"
},{
id: 2,
child:[3],
data : "I m second"
},
{
id: 3,
child:[],
data : "I m third"
},
{
id: 4,
child:[6],
data : "I m fourth"
},{
id: 5,
child:[],
data : "I m fifth"
},{
id: 6,
child:[],
data : "I m sixth"
}];
我已將此對象轉換為
var newObj = [{
id: 1,
child: [{
id: 2,
child: [{
id: 3,
child: [],
data: "I m third"
}],
data: "I m second"
}, {
id: 4,
child: [{
id: 6,
child: [],
data: "I m sixth"
}],
data: "I m fourth"
}],
data: "hello"
}, {
id: 5,
child: [],
data: "I m fifth"
}];
這只不過是基於每個屬性的子數組的 JSON 樹格式。 如何解決問題? 如何在javascript中編碼?
任何幫助將是可觀的。 提前致謝。
帶有臨時對象的提案,用於保留對項目的引用。
var array = [{ id: 1, child: [2, 4], data: "hello" }, { id: 2, child: [3], data: "I m second" }, { id: 3, child: [], data: "I m third" }, { id: 4, child: [6], data: "I m fourth" }, { id: 5, child: [], data: "I m fifth" }, { id: 6, child: [], data: "I m sixth" }], tree = []; array.forEach(function (a) { if (!this[a.id]) { this[a.id] = { id: a.id }; tree.push(this[a.id]); } this[a.id].data = a.data; this[a.id].child = a.child.map(function (b) { this[b] = this[b] || { id: b }; return this[b]; }, this); }, Object.create(null)); document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
好吧……正如我所評論的,這是一個很好的問題,很高興能對此進行一些思考。 顯然,這比展平嵌套對象數組更難。
順便說一下,該算法不依賴於對象的 id 和數組中的對象鍵之間的任何相關性。 具有任何 id 的對象可以位於數組中的任何位置。
var obj = [{ id: 1, child: [2, 4], data: "hello" }, { id: 2, child: [3], data: "I m second" }, { id: 3, child: [], data: "I m third" }, { id: 4, child: [6], data: "I m fourth" }, { id: 5, child: [], data: "I m fifth" }, { id: 6, child: [], data: "I m sixth" }]; function construct(flat){ function nest(o) { o.forEach( c => { if (!!c.child.length) { // coolness starts here c.child = c.child.map( e => flat.splice(flat.findIndex( f => f.id == e),1)[0]); nest(c.child); } }); } nest(flat); return flat; } document.write("<pre>" + JSON.stringify(construct(obj), null, 2) + "</pre>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.