Search code examples
javascriptjsonreact-nativenestedlogic

Deleting object from nested JSON by name provided.It should return the rest


Hi I am new to react native,I am having a array of objects ,I want to delete the a inner object from this JSON.

[
  {
    Key: 1,
    exchnageArr: [
      {
        name: ”FX”
      },
      {
        name: ”MK”
      }
    ]
  },
  {
    Key: 2,
    exchnageArr: [
      {
        name: ”CK”
      },
      {
        name: ”DK”
      }
    ]
  }
]

Here I want to delete the {name:"FX"} from this JSON .If I pass "FX".How to do this,I tried but not working for me.


    const newDatavalues = arr.forEach((item) =>
            item.exchangeArr.forEach((subItem, index) => {
              if (subItem.name === "FX") {
               return item.exchangeArr.splice(index, 1);
           } 
       })
     );


Solution

  • You could use Array#filter on each array inside one of the objects.

    let arr=[{Key:1,exchnageArr:[{name:"FX"},{name:"MK"}]},{Key:2,exchnageArr:[{name:"CK"},{name:"DK"}]}];
    for (const o of arr)
      o.exchnageArr = o.exchnageArr.filter(x => x.name !== 'FX');
    console.log(arr);