Skip to content
Advertisement

Update array based on id Javascript

I want to update he array based on id with some conditions. Conditions were =

 const data1 = [
    { type:"foo", id:"123"},
    { type:"bar", id:"124"},
    ]

const update1 = {type:"bar",id:"123"}
const update2 = {type:"foo", id:"125"}
const update3 = {type:"bar", id:"123"}
  1. console.log(myupdate(data1, update1))

should update the data1 as bellow based on id here the type is changed to bar

data1 = [ { type:"bar", id:"123"},
          { type:"bar", id:"124"}, ] 
       
  1. console.log(myupdate(data1, update2))

here as no item with id 125 exist so it adds a new one

data1 = [ { type:"bar", id:"123"},
          { type:"bar", id:"124"},
          { type:"foo", id:"125"} ] 
      
      
  1. console.log(myupdate(data1, update3))

here type is not changed so it should return the array as it is.

data1 = [{ type:"bar", id:"123"},
         { type:"bar", id:"124"},
         { type:"foo", id:"125"}
] 

I have tried this code but it doesn’t work

const myupdate = (arr, element) => {
arr.map((item)=>{
console.log(item, "ele",element)
 if(item.id != element.id){
  arr.push(element)
  return
 }
 if(item.id === element.id && item.type === element.type){
 return
 }
 if(item.id === element.id && item.type != element.type){
  arr.filter(item => item !== element).push(element)
  return
 }
})
}

Advertisement

Answer

You need to look through the array and find the correct item. If there is no item with the specified requirement, you’ll add a new one. Here is an example:

const data = [
  { type: "foo", id: "123"},
  { type: "bar", id: "124"},
]

const update = (data, value) => {
  console.log('Updating/Inserting', value);
  const existingItem = data.find(item => item.id === value.id);
  if (existingItem === undefined) {
    data.push(value);
  } else {
    existingItem.type = value.type;
  }
}

console.log('before', data);
update(data, {type:"bar",id:"123"});
console.log(data);
update(data, {type:"foo", id:"125"});
console.log(data);
update(data, {type:"bar", id:"123"});
console.log(data);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement