【问题标题】:How to update matched item with depth more of first?如何更新匹配项的深度更多?
【发布时间】:2020-07-31 06:14:48
【问题描述】:

This example 有一个很好的理由来更新对象。但是有一个问题,这只适用于同一级别(深度)的对象。

我怎样才能做同样的事情,但更多的一级,深度?

我在这里有一个示例对象:

let globalObj = [
    {
      fam_id: 1, // Random unique ID's.
      name: "No name",
      attributes: {
        "Key2": "*",
        "Key3": "*",
      },
      children: [
        {
          fam_id: 2, // Random unique ID's.
          name: "No name 2",
          attributes: {
            "Key2": "*",
            "Key3": "*",
          },
        },
      ],
    },
  ]

我在这里有对象来更新全局,例如:

let updateObj = {        
        fam_id: 2, // Mathed ID!
        name: "No name 3",
        attributes: {
            "Key2": "*",
            "Key3": "*",
         },
},

findIndexslice 方法效果很好,但是对于深度 0? 如何过滤更多深度为0的? 1个或更多怎么样?

谢谢! o/

【问题讨论】:

    标签: javascript arrays object filter


    【解决方案1】:

    您可以通过使用递归函数来完成此操作

    let globalObj = [
        {
          fam_id: 1, // Random unique ID's.
          name: "No name",
          attributes: {
            "Key2": "*",
            "Key3": "*",
          },
          children: [
            {
              fam_id: 2, // Random unique ID's.
              name: "No name 2",
              attributes: {
                "Key2": "*",
                "Key3": "*",
              },
            },
          ],
        },
      ];
    
    let updateObj = {        
            fam_id: 2, // Mathed ID!
            name: "No name 3",
            attributes: {
                "Key2": "*",
                "Key3": "*",
             },
    };
    
    // recursive function
    matchAndUpdate = (updater, target) => {
        if (updater.fam_id === target.fam_id) {
            target.name = updater.name;
            target.attributes = updater.attributes;
        }
        
        if ("children" in target && Array.isArray(target.children)) {
            target.children.forEach(child => {
                matchAndUpdate(updater, child);
            });
        }
    }
    
    globalObj.forEach(g => {matchAndUpdate(updateObj,g )});
    
    document.getElementById('x').innerText = JSON.stringify(globalObj,null,"\t");
    pre {
      background-color: #456;
      color: #FED;
      font-size: small;
    }
    <pre><code id="x"></code></pre>

    【讨论】:

    猜你喜欢
    • 2019-11-05
    • 2021-08-07
    • 2019-03-14
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多