简体   繁体   中英

Push and replace the value in array

I am creating a project using Angular. During the development, I am facing a problem when pushing values to my array. My requirement is that I want to push the value to the array unless the value already exists in the array. If it already exists, then simply replace that value with newer value.

This is my code, which is currently not working:

var obj = {
   question_id: "1",
   id: "2",
   "question": "This is a test"
};

This is the object that I want to push:

this.selectedOptions = [];

if (!this.selectedOptions.some(function(entry) { return entry.question_id === category.question_id;})) {
    this.selectedOptions.push(category);
}

Your code will push the item to the array, but it won't replace an existing item. I'm assuming that its an array of objects, given the entry.question_id part.

What you need is to check if the object exists in the array, and update or push it accordingly. The findIndex method will return the object index, if it exists in the array, or -1 if not.

const entryIndex = this.selectedOptions.findIndex(entry => entry.question_id === category.question_id);
if (entryIndex > -1) {
  this.selectedOptions[entryIndex] = category;
} else {
  this.selectedOptions.push(category);
}

You could find the index for update or push something new.

let index = this.selectedOptions.findIndex(function (entry) {
    return entry.question_id === category.question_id;
});

if (index === -1) {
    this.selectedOptions.push(category);
} else {
    this.selectedOptions[index].someKey = 'someValue';
}

Try this:

function customUpsert(arr, data) {
   const index = arr.findIndex((e) => e.id === data.id);

   if (index === -1) {
      arr.push(data);
   } else {
      arr[index] = data;
   }
}

Following funcntion checks if "oldVal" exists and replace it with the "newVal" if it does.

 var selectedOptions = [1, 2, 3]; function replaceOrAppend(oldVal, newVal) { let idx = selectedOptions.indexOf(oldVal); if (idx < 0) selectedOptions.push(newVal) else selectedOptions[idx] = newVal; } replaceOrAppend(1, 100); replaceOrAppend(10, 200); console.log(selectedOptions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM