我有一个对象数组,当Id匹配时,我想在数组的特定对象中添加键。我试过了:
this.data.forEach(value => {
if (value.Id === attachmentDataId) {
AttachmentTypeId: this.attachmentRecord.AttachmentType;
}
});
但是它没有工作也没有给出任何错误
试一下:
let data = [{ id: 1 }, { id: 5 }];
const attachmentDataId = 5;
const attachmentRecord = { AttachmentType: "AttachmentType" };
data.forEach(value => {
if (value.id === attachmentDataId) {
value.AttachmentTypeId = attachmentRecord.AttachmentType;
}
});
stackblitz示例:https://stackblitz.com/edit/js-nrhouh
您可以使用forEach
函数的index
参数来访问数组的特定对象。
this.data.forEach((value, i) => {
if (value.Id === attachmentDataId) {
this.data[i] = {
...this.data[i],
AttachmentTypeId: this.attachmentRecord.AttachmentType
};
}
});
在if
块中,您也可以使用
this.data[i]['AttachmentTypeId'] = this.attachmentRecord.AttachmentType;
我发现使用展开运算符更简洁。
使用javascript map()方法。Map()返回一个新数组,它接受一个回调,迭代数组中的每个元素
const updatedData = data.map(res => {
if(res.id === attachmentDataId) {
res.AttachmentTypeId = attachmentRecord.AttachmentType;
}
return res
})