skip to Main Content

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);
           } 
       })
     );

2

Answers


  1. You have a typo (exchnageArr, that should be exchangeArr) in your property names in the array (JSON).

    Corrected JSON:

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

    Now your code should work fine.

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search