代码之家  ›  专栏  ›  技术社区  ›  Niladri Banerjee - Uttarpara

如何通过lodash从内部对象中移除关键帧

  •  0
  • Niladri Banerjee - Uttarpara  · 技术社区  · 3 年前
    var result = [
        {
            color: "blue",
            users: [
                {
                    "name": "John",
                    "color": "blue",
                    "age": "29"
                },
                {
                    "name": "Neil",
                    "color": "blue",
                    "age": "34"
                }
            ]
        },
        {
            color: "green",
            users: [
                {
                    "name": "Ronn",
                    "color": "green",
                    "age": "50"
                }
            ]
        }
    ]
    

    我想删除 color users . 为此,我用Lodash编写了以下代码片段。

    var result = _.omit(result.users, ['color']);
    

    { ... }

    [
            {
                color: "blue",
                users: [
                    {
                        "name": "John",
                        "age": "29"
                    },
                    {
                        "name": "Neil",
                        "age": "34"
                    }
                ]
            },
            {
                color: "green",
                users: [
                    {
                        "name": "Ronn",
                        "age": "50"
                    }
                ]
            }
        ]
    
    2 回复  |  直到 3 年前
        1
  •  2
  •   DecPK    3 年前

    您必须在数组上循环并使用 omit

    Arguments of omit is

    1) 对象:源对象。

    [paths]((string | string[]):要忽略的属性路径。

    Return value

    (对象):返回新对象。

    const clone = result.map((obj) => ({
        ...obj,
        users: obj.users.map((o) => _.omit(o, ["color"])),
    }));
    

    Codesandbox Demo

    map 作为:

    var result = [
      {
        color: "blue",
        users: [
          {
            name: "John",
            color: "blue",
            age: "29",
          },
          {
            name: "Neil",
            color: "blue",
            age: "34",
          },
        ],
      },
      {
        color: "green",
        users: [
          {
            name: "Ronn",
            color: "green",
            age: "50",
          },
        ],
      },
    ];
    
    const res = result.map((obj) => ({ ...obj, users: obj.users.map(({ color, ...rest }) => rest)}));
    console.log(res);