Home > Blockchain >  How to Filter Nested Object Array Without affecting References in JavaScript
How to Filter Nested Object Array Without affecting References in JavaScript

Time:01-20

Just want to remove all the items other than 14 from the parentId: 1001 and add that item to another object.

I want to filter the array without affecting the source array.

var Data = [{
    "id": 1001,
    "text": "A",
    "items": [
      { "id": 13, "text": "Thirteen" }, 
      { "id": 14, "text": "Fourteen" }, 
      { "id": 15, "text": "Fifteen", }
    ]
  },
  {
    "id": 1002,
    "text": "B",
    "items": [
      { "id": 21, "text": "TwentyOne" }, 
      { "id": 22, "text": "TwentyTwo" }, 
      { "id": 23, "text": "TwentyThree", }
    ]
  }
]

var childId = 14;
Data.items.filter((x) => {
  return x.id != childId;
})

//this is affecting the source array (Data)
//after searching on internet found a solution
Data.items.filter((x) => {
  return x.id childId;
}).map(function(x) {
  return x
});

CodePudding user response:

Your Data has no items property: it is an array, so you actually have Data[0].items, Data[1].items, ...

NB: it is common practice to use camelCase for such variable names, and reserve PascalCase for constructors/classes

Here is how you could do it:

const data = [{"id": 1001,"text": "A","items": [{ "id": 13, "text": "Thirteen" }, { "id": 14, "text": "Fourteen" }, { "id": 15, "text": "Fifteen", }]},{"id": 1002,"text": "B","items": [{ "id": 21, "text": "TwentyOne" }, { "id": 22, "text": "TwentyTwo" }, { "id": 23, "text": "TwentyThree", }]}]

const childId = 14;
const newData = data.map(obj => ({
    ...obj,
    items: obj.items.filter(x => x.id != childId)
}));
console.log(newData);

CodePudding user response:

As you want to filter out a few items from an array object and want to add those into another object.

You can also achieve this requirement by doing a deep copy of an original array with the help of structuredClone() API and then iterating it using Array#forEach method.

Live demo :

const data=[
  {
    "id":1001,
    "text":"A",     
    "items":[
      {
        "id":13,
        "text":"Thirteen"
      },
      {
        "id":14,
        "text":"Fourteen"            
      },
      {
        "id":15,
        "text":"Fifteen",            
      }
    ]

  },
  {
    "id":1002,
    "text":"B",     
    "items":[
      {
        "id":21,
        "text":"TwentyOne"
      },
      {
        "id":22,
        "text":"TwentyTwo"            
      },
      {
        "id":23,
        "text":"TwentyThree",            
      }
    ]     
  }
];

const clone = structuredClone(data);
let remainingItems = [];

clone.forEach(obj => {
    if (obj.id === 1001) {
    remainingItems = obj.items.filter(({ id }) => id !== 14);
    obj.items = obj.items.filter(({ id }) => id === 14);
  } else {
    obj.items = [...obj.items, ...remainingItems];
  }
})

console.log('cloned data_____', clone);
console.log('source data_____', data);

  • Related