Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading