我只需要查看单个节点即可重新创建多维对象数组。
我尝试在循环(Array.map)中使用递归函数。
obj = [{
key: 0,
children: [{
key: 1,
children: [{
key: 2,
children: [{
key: 3,
children: []
},
{
key: 4,
children: []
}]
},
{
key: 5,
children: [{
key: 6,
children: []
},
{
key: 7,
children: []
},
{
key: 8,
children: []
}]
}]
}]
}]
function test(arg, level=0, arry=[]){
arg.map((data, i) => {
if(!data.arry){
arry.push(data.key);
data.arry = arry;
}
if(data.children){
test(data.children, level+1, data.arry);
}
})
}
test(obj);
函数 test 应该构建并返回与 obj 完全相同的对象。 这只是我遇到的问题的简化版本,这就是为什么它看起来很奇怪的原因(返回我已经拥有的对象)。我最初的问题是关于从数据库中获取对象的n维数组的一部分,但不知道其原始维。因此,我必须“发现”尺寸,然后建立与对象完全相同的副本。
答案 0 :(得分:0)
一个示例实现是这样的:递归地遍历数组和对象,并深度复制它们的属性/子对象。这将创建对象的深层副本,并测试数据是否已实际复制,而不再是引用:
obj = [{
key: 0,
children: [{
key: 1,
children: [{
key: 2,
children: [{
key: 3,
children: []
},
{
key: 4,
children: []
}]
},
{
key: 5,
children: [{
key: 6,
children: []
},
{
key: 7,
children: []
},
{
key: 8,
children: []
}]
}]
}]
}];
function copy(obj) {
let copiedObject;
if (Array.isArray(obj)) {
// for arrays: deep-copy every child
copiedObject = [];
for (const child of obj) {
copiedObject.push(copy(child));
}
} else if (typeof obj === 'object') {
// for objects: deep-copy every property
copiedObject = {};
for (const key in obj) {
copiedObject[key] = copy(obj[key]);
}
} else {
// for primitives: copy the value
return obj;
}
return copiedObject;
}
function test() {
const cpy = copy(obj);
// make sure that deep-copying worked
console.log('Values from obj should be exactly copied to cpy: ' + (cpy[0].children[0].children[0].key === obj[0].children[0].children[0].key));
// make sure that references are broken, so that when data from the original object is updated, the updates do
// NOT reflect on the copy
obj[0].children[0].children[0].key = Math.random();
console.log('Changes to obj should not reflect on cpy: ' + (cpy[0].children[0].children[0].key !== obj[0].children[0].children[0].key));
}
test();