【问题标题】:How to remove a key from inner object through lodash如何通过lodash从内部对象中删除键
【发布时间】:2022-01-20 21:58:33
【问题描述】:
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"
            }
        ]
    }
]

我想删除users 下的color 键。为此,我在 Lodash 中编写了以下代码 sn-p。

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

但它给了我以下{ ... }

如何才能实现如下输出?

[
        {
            color: "blue",
            users: [
                {
                    "name": "John",
                    "age": "29"
                },
                {
                    "name": "Neil",
                    "age": "34"
                }
            ]
        },
        {
            color: "green",
            users: [
                {
                    "name": "Ronn",
                    "age": "50"
                }
            ]
        }
    ]

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    你必须遍历数组并使用omit

    Arguments of omit is

    1)对象:源对象。

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

    Return value

    (Object):返回新对象。

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

    现场演示

    您可以使用 map 使用 vanilla JS 轻松实现结果:

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

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 2014-07-18
      • 1970-01-01
      • 2018-06-13
      • 2016-01-03
      • 2018-07-06
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多