Javascript-将带有子对象的对象转换为类似于steps的数组



我有一个对象:

const data = {
name: 'root',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
children: [
{
name: 'child',
attributes: [{}],
},
],
},
{
name: 'child',
attributes: [{}],
},
],
};

我想把它们转换成一个类似step的数组,其中数组(step(的每个元素都有以前步骤中的元素和一个新的子元素。

示例:

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: [{}],
},
],
}
]

我试图使用递归函数来实现这一点,但在保留父元素和正确的结构方面遇到了问题。

如果需要更多信息,请告诉我。

提前感谢!

树和递归是齐头并进的。基本上,首先我遍历树(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;
}

最新更新