如何在基于另一个对象的嵌套对象数组中添加键

时间:2020-01-13 17:50:48

标签: javascript object

我有一个名为results的对象数组,并且该对象的键是editKeyValues对象的键值,并且需要在编辑键中添加值。以下是输入

var result =  [{
  name  :  'database',
  checked : true,
  key :  1,
  schemas  : [
    {
      name  : "schema2",
      checked : true,
      key : 6,
      tables : [
        {
          name  : "table2",
          checked : true,
          key : 7,
          columns : [
            {
              name  : "column1",
              checked : true,
              key : 8,
            }
          ]
        },
      ]
    },

  ]
}]

var editKeyValues = { 8 : "column4", 6 : "schema4"}

我想要的以下格式的输出

    var result =  [{
      name  :  'database',
      checked : true,
      key :  1,
      schemas  : [
{
  name  : "schema2",
  checked : true,
  key : 6,
  edit : "schema4"
  tables : [
    {
      name  : "table2",
      checked : true,
      key : 7,
      columns : [
        {
          name  : "column1",
          checked : true,
          key : 8,
          edit : "column4"     // value of key 8 from editkeyValues array
        }
      ]
    },
  ]
},]}]

为我提供一种最佳方法,因为结果中有大量数据对象...递归是一个好主意吗???帮助我找出最佳方法。

2 个答案:

答案 0 :(得分:0)

您可以使用Map并迭代对象并搜索嵌套数组。

如果没有更多的节点有资格进行更新,则此方法会短路。

function update(array, nodes) {
    return array.some(o => {
        var key = o.key.toString();
        if (nodes.has(key)) {
            o.edit = nodes.get(key);
            nodes.delete(key);
            if (!nodes.size) return true;
        }
        return update(Object.values(o).find(Array.isArray) || [], nodes);
    });
}

var data = [{ name: 'database', checked: true, key: 1, schemas: [{ name: "schema1", checked: true, key: 2, tables: [{ name: "table1", checked: true, key: 3, columns: [{ name: "column2", checked: true, key: 5 }] }] }, { name: "schema2", checked: true, key: 6, tables: [{ name: "table2", checked: true, key: 7, columns: [{ name: "column1", checked: true, key: 8 }] }] }] }],
    keyValues = { 8: 'column4', 6: 'schema4' };

update(data, new Map(Object.entries(keyValues)));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

let data = [{
  name: 'database',
  checked: true,
  key: 1,
  schemas: [
    {
      name: "schema2",
      checked: true,
      key: 6,
      tables: [
        {
          name: "table2",
          checked: true,
          key: 7,
          columns: [
            {
              name: "column1",
              checked: true,
              key: 8,
            }
          ]
        },
      ]
    },
  ]
}];
let schemas = data.flatMap(d => d.schemas);
let tables = schemas.flatMap(s => s.tables);
let columns = tables.flatMap(t => t.columns);
let flatData = [data, schemas, tables, columns].flat();

let editKeyValues = {8: "column4", 6: "schema4"};
Object.entries(editKeyValues).forEach(([key, newName]) =>
    flatData.find(obj => obj.key === parseInt(key)).edit = newName);

console.log(data);