Skip to content
Advertisement

How to remove a key from inner object through lodash

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"
            }
        ]
    }
]

I want to delete the color key under users. For this, I have written the following code snippet in Lodash.

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

But it gives me the following { ... }

How can achieve the following output?

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

Advertisement

Answer

You have to loop over the array and use omit

Arguments of omit is

1) object: The source object.

2) [paths] (…(string|string[])): The property paths to omit.

Return value

(Object): Returns the new object.

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

Live Demo

Codesandbox Demo

You can easily achieve the result using vanilla JS using map as:

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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement