根据angular中的相同id更新数组中的值 [英] Update value in array based on same id in angular
本文介绍了根据angular中的相同id更新数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组
const buildings = [
{ id: 111, status: false, image: 'Test1' },
{ id: 334, status: true, image: 'Test4' },
{ id: 243, status: false, image: 'Test7' },
{ id: 654, status: false, image: 'Test9' },
{ id: 222, status: true, image: 'Test8' }
];
我需要基于新的porperti更新相同的值
What I need is to update same value based on new porperti
cons newBuilding = { id: 111, status: true, image: 'Test1' };
我需要一个可以像这样处理的函数
I need a function that will handle like that like this
mergeSelectedBuildings(building) {
if (buildings.length >= 0) {
buildings.push(building);
} else {
buildings.map((buildingValue, i) => {
if (buildingValue.id === building.id) {
this.buildings[i].status = building.status;
this.buildings[i].image = building.image;
} else {
this.buildings.push(building);
}
});
}
}
问题是,这无法按预期工作,它总是添加新的值并且不会更新:(
The problem is that this does not work as expected, it always add new and new value it does not update:(
推荐答案
我不会像这样使用 map
数组函数.而是,尝试找到该项目并更新该对象.如果找不到该项目,则将建筑物推入阵列.
I wouldn't use the map
array function like this. Instead, try to find the item and update that object. If the item isn't found, push the building to the array.
mergeSelectedBuildings(building) {
const existing = this.selectedBuildings.find(x => x.id === building.id);
if (existing) {
existing.status = building.status;
existing.image = building.image;
} else {
this.selectedBuildings.push(building);
}
}
这篇关于根据angular中的相同id更新数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文