[Fixed] Filtering array inside json

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.

  1. Using destructure object combined with Spread ... operator.
  2. "only one element with name "child3"" –> Find childArrayby usingArray#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);

Leave a Reply

(*) Required, Your email will not be published