首页 > 解决方案 > 推送并替换数组中的值

问题描述

我正在使用 Angular 创建一个项目。在开发过程中,我在将值推送到我的数组时遇到了问题。我的要求是我想将值推送到数组中,除非该值已经存在于数组中。如果它已经存在,那么只需将该值替换为较新的值。

这是我的代码,目前不工作:

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

这是我要推送的对象:

this.selectedOptions = [];

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

标签: javascriptangular

解决方案


您的代码会将项目推送到数组中,但不会替换现有项目。我假设它是一个对象数组,给定entry.question_id部分。

您需要检查该对象是否存在于数组中,并相应地更新或推送它。findIndex方法将返回对象索引,如果它存在于数组中,否则返回 -1

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

推荐阅读