Home > Software engineering >  Find and replace element in array on the basis of id
Find and replace element in array on the basis of id

Time:06-21

I have an array as follows:

[
{
  "id":1,
  "active":1,
  "name":"paris"
},
{
  "id":2,
  "active":0,
  "name":"london"
},
{
  "id":3,
  "active":1,
  "name":"Australia"
},
{
  "id":4,
  "active":0,
  "name":"india"
}
]

I have a method which recieved a object as argument. object looks something like this:

 {
      "id":4,
      "active":0,
      "name":"india"
    }

In that method I want to check if element with particular id is present or not. If present I want to replace element in array with the element received in arguments. If element with that id is not found that add that element to the array. How can I do that?

CodePudding user response:

you can do like this

let testArr = [
  {
    id: 1,
    active: 1,
    name: "paris",
  },
  {
    id: 2,
    active: 0,
    name: "london",
  },
  {
    id: 3,
    active: 1,
    name: "Australia",
  },
  {
    id: 4,
    active: 0,
    name: "india",
  },
];

let testObj = {
  id: 4,
  active: 0,
  name: "india1",
};

let findIndex = testArr.findIndex((data) => data.id === testObj.id);
if (findIndex != -1) {
  testArr[findIndex].active = testObj.active;
  testArr[findIndex].name = testObj.name;
} else {
  testArr = [...testArr, testObj];
}
console.log("testArr=>", testArr);

CodePudding user response:

I'd propose the following: in any case you want to have the new object included in the given array:

  1. Remove Object with id from array
  2. Add new Object

Could work as following:

let testArr = [ ... ]
let testObj = { ... }

testArr = testArr.filter(element => element.id !== testObj.id)
testArr.push(testObj)

If it's necessary to keep the object in the array:

let testArr = [ ... ]
let testObj = { ... }

const foundElement = testArr.find(element => element.id === testObj.id)
if (foundElement) {
  foundElement.active = testObj.active
  foundElement.name = testObj.name
} else {
  testArr.push(testObj)
}
  • Related