我有一個物件:
const data = {
name: 'root',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
},
],
},
{
name: 'child',
attributes: [{}],
},
],
};
而且我想將它們轉換為類似步驟的陣列,其中陣列(步驟)的每個元素都有來自先前步驟的元素和一個新的子元素。
例子:
const steps = [
{
name: 'root',
attributes: [{}],
},
{
name: 'root',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
},
],
},
{
name: 'root',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
},
],
},
],
},
{
name: 'root',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
},
],
},
{
name: 'child',
attributes: [{}],
},
],
}
]
我正在嘗試使用遞回函式來做到這一點,但是在保持父元素和正確的結構方面存在問題。
讓我知道是否需要更多資訊。
提前致謝!
uj5u.com熱心網友回復:
樹和遞回齊頭并進。基本上,首先我遍歷樹(iterate),將每個專案推向一個陣列(result)。我還存盤每個專案的父項。
下一步,我按順序傳遞該陣列,并total通過將每個專案添加到其正確位置來重建物件。逐個。然后我們將它克隆到一個結果 ( result_for_real) 陣列中。下一項。重建。克隆。等等
const data = {
name: 'root',
attributes: [{}],
children: [{
name: 'child 1',
attributes: [{}],
children: [{
name: 'grandchild',
attributes: [{}],
}],
},
{
name: 'child 2',
attributes: [{}],
},
],
};
function create_steps(obj) {
var result = []
function iterate(obj, parent) {
parent = parent || null
var step = {
name: obj.name,
attributes: obj.attributes
}
result.push({step, parent});
(obj.children || []).forEach(function(child) {
iterate(child, step)
});
}
iterate(obj)
function clone(obj) {
return JSON.parse(JSON.stringify(obj))
}
var result_for_real = [];
var total = {}
result.forEach(function(item) {
if (item.parent === null) {
total = item.step;
} else {
item.parent.children = item.parent.children || []
item.parent.children.push(item.step)
}
result_for_real.push(clone(total));
})
return result_for_real;
}
console.log(create_steps(data))
.as-console-wrapper {
max-height: 100% !important;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504629.html
標籤:javascript 节点.js 数组 循环
上一篇:如何停止回圈?
