javascript - 推送并替换数组中的值
问题描述
我正在使用 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);
}
解决方案
您的代码会将项目推送到数组中,但不会替换现有项目。我假设它是一个对象数组,给定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);
}
推荐阅读
- google-apps-script - 如何在我的数据输入表单中只为 Google Sheet App Script 按钮创建一个必填字段?
- python - 有没有一种方法可以仅使用 pandas 将公式写入 .xlsx 文件,即不使用 xlsxwriter / openpyxl 之类的工具?
- schemaspy - Schemaspy 中的自定义输出生产者
- python - send_code_request (Telethon) 之后的无休止更新
- python - 是否可以在 Django 模型中的复选框或下拉列表下添加依赖文本和日期字段
- c# - 从 SQL 数据库中检索数据并使用动态创建的标签来显示 Ping 结果
- r - R包在两个版本号之间导入包?
- bash - 如果目录存储在变量中,那么在引用它时表示其子目录的正确方法是什么?
- node.js - 如何从 mongodb 获取和显示没有未定义值的所有值?
- reactjs - 在其中键入任何值时关闭模态?