【问题标题】:Compare JSON tree items with arrays of objects将 JSON 树项与对象数组进行比较
【发布时间】:2021-06-21 11:46:47
【问题描述】:

我有以下树结构示例:

const tree = {
  units: [
    {
      id: 482,
      units: [
        {
          id: 483,
        },
      ],
      entities: [
        {
          id: 318,
          portfolios: [
            {
              id: 356,
            },
            {
              id: 357,
            },
          ],
        },
        {
          id: 319,
          portfolios: [
            {
              id: 358,
            },
          ],
        },
      ],
    },
  ],
};

以及以下对象数组:

const units = [
      {
        id: 483
      },
    ];
const entities = [
  {
        id: 319
      },
];
const portfolios = [
  {
        id: 358
      },
];

我需要找到一种方法来解析包含所有 3 个数组(单位、实体、投资组合)的整个树,如果数组中的某个项目的 id 与树内的一个 id 匹配,我应该添加一个标志(例如找到 = true)。

在这个解析函数之后,我希望输出看起来像这样:

 const tree = {
  units: [
    {
      id: 482,
      units: [
        {
          id: 483,
          found: true
        },
      ],
      entities: [
        {
          id: 318,
          portfolios: [
            {
              id: 356,
            },
            {
              id: 357,
            },
          ],
        },
        {
          id: 319,
          found: true,
          portfolios: [
            {
              id: 358,
              found: true,
            },
          ],
        },
      ],
    },
  ],
};

谁能告诉我最好的解决方案?谢谢!

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6 tree


    【解决方案1】:

    您可以使用递归函数来更新结构:

    const tree = {units: [{id: 482, units: [{id: 483,},], entities: [{id: 318, portfolios: [{id: 356,},{id: 357,},],},{id: 319, portfolios: [{id: 358,},],},],},],};
    const units = [{id: 483},];
    const entities = [{id: 319},];
    const portfolios = [{id: 358},];
    var vals = {units:units, entities:entities, portfolios:portfolios};
    function update_tree(d, parent = null){
       if (d.constructor === Array){
          for (var i of d){
             update_tree(i, parent = parent)
          }
       }
       else if (d.constructor === Object){
          if (parent != null && parent in vals){
             if (vals[parent].some(function(x){return Object.keys(x).some(function(y){return y in d && d[y] === x[y]})})){
                d['found'] = true;
             }
          }
          for (var i of Object.keys(d)){
             update_tree(d[i], parent = i)
          }
       }
    }
    update_tree(tree)
    console.log(tree)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多