首页 > 解决方案 > 在 JavaScript 中映射多维对象数组

问题描述

我只需要通过查看单个节点来重新创建对象的多维数组。

我尝试在循环(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完全相同的对象。这只是我遇到的问题的简化版本,这就是为什么它看起来很奇怪(返回我已经拥有的对象)。我最初的问题是关于从 DB 中获取部分 n 维对象数组,但不知道其原始尺寸。所以我必须“发现”尺寸,然后构建完全相同的对象副本。

标签: javascriptarraysmultidimensional-arrayarrayobject

解决方案


一个示例实现是这样的:递归迭代数组和对象并深度复制它们的属性/子项。这会创建对象的深层副本,并测试数据是否实际被复制而不是引用:

 

   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();


推荐阅读