Issue
I have one JSON which is as follows.
{
"id":"1",
"name":"name1",
"type":"abc",
"childArray":[
{
"id":"abc",
"name":"child1",
"type":"abc"
},
{
"id":"efg",
"name":"child2",
"type":"abc"
},
{
"id":"xyz",
"name":"child3",
"type":"abc"
},
{
"id":"drs",
"name":"child4",
"type":"abc"
}
]
}
In this JSON I have a childArray
and some more content after childArray
. I want to have this Json and in childArray
I want to have only one element with the name "child3"
, the rest of the content should be the same.
How can I do that?
Solution
Ok, the solution seems like this.
- Using
destructure object
combined withSpread ...
operator. - "only one element with name "child3"" –> Find childArray
by using
Array#find`
const obj = {"id":"1","name":"name1","type":"abc","childArray":[{"id":"abc","name":"child1","type":"abc"},{"id":"efg","name":"child2","type":"abc"},{"id":"xyz","name":"child3","type":"abc"},{"id":"drs","name":"child4","type":"abc"}]};
const {childArray = [], ...others} = obj;
const result = {...others, childArray: [childArray.find(r => r.name === "child3")]};
console.log(result);