0

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
 }
})
}
1
  • You don't return anything from your function so console.log() will always log undefined (the default return value of a function). You are also mutating the array passed as a parameter rather than returning a new array. Commented Jul 20, 2021 at 11:41

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.