Home > Back-end >  Remove value from nested array item react native
Remove value from nested array item react native

Time:05-18

I have below array format:

[
  {
    "category": "c8kr0cv012vtr8vm3iqg",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8tjghovq0ahq4ccf980",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  },
  {
    "category": "c8kr0cv012vtr8vm3ivg",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8tjghovq0ahq4ccf980",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  },
  {
    "category": "c8kr0cv012vtr8vm3is0",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  },
  {
    "category": "c8kr0cv012vtr8vm3ir0",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8tjghovq0ahq4ccf980",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  }
]

I want to remove value from subcategory array for example c8tjghovq0ahq4ccf980

I tried below code:

tempPayload.some(function (a) {
  return a.subcategories.some(function (b, i, bb) {
    if (b === "c8tjghovq0ahq4ccf980") {
      bb.splice(i, 1);
      return true;
    }
  });
});

But it is not working any idea how can I resolve this?

CodePudding user response:

Try with following code:

tempPayload.map((item) => {
  const index = item.subcategories.indexOf("c8tjghovq0ahq4ccf980");
  if (index > -1) {
    item.subcategories.splice(index, 1);
  }
});

CodePudding user response:

for(let i=0; i<tempPayload.length; i  ){
  tempPayload[i].subcategories = tempPayload[i].subcategories.filter(i => i!==  "c8tjghovq0ahq4ccf980")
}
console.log(tempPayload)
  • Related