JavaScript
x
28
28
1
var result = [
2
{
3
color: "blue",
4
users: [
5
{
6
"name": "John",
7
"color": "blue",
8
"age": "29"
9
},
10
{
11
"name": "Neil",
12
"color": "blue",
13
"age": "34"
14
}
15
]
16
},
17
{
18
color: "green",
19
users: [
20
{
21
"name": "Ronn",
22
"color": "green",
23
"age": "50"
24
}
25
]
26
}
27
]
28
I want to delete the color
key under users
. For this, I have written the following code snippet in Lodash.
JavaScript
1
2
1
var result = _.omit(result.users, ['color']);
2
But it gives me the following { ... }
How can achieve the following output?
JavaScript
1
25
25
1
[
2
{
3
color: "blue",
4
users: [
5
{
6
"name": "John",
7
"age": "29"
8
},
9
{
10
"name": "Neil",
11
"age": "34"
12
}
13
]
14
},
15
{
16
color: "green",
17
users: [
18
{
19
"name": "Ronn",
20
"age": "50"
21
}
22
]
23
}
24
]
25
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.
JavaScript
1
5
1
const clone = result.map((obj) => ({
2
obj,
3
users: obj.users.map((o) => _.omit(o, ["color"])),
4
}));
5
Live Demo
You can easily achieve the result using vanilla JS using map
as:
JavaScript
1
30
30
1
var result = [
2
{
3
color: "blue",
4
users: [
5
{
6
name: "John",
7
color: "blue",
8
age: "29",
9
},
10
{
11
name: "Neil",
12
color: "blue",
13
age: "34",
14
},
15
],
16
},
17
{
18
color: "green",
19
users: [
20
{
21
name: "Ronn",
22
color: "green",
23
age: "50",
24
},
25
],
26
},
27
];
28
29
const res = result.map((obj) => ({ obj, users: obj.users.map(({ color, rest }) => rest)}));
30
console.log(res);