我有一个已加载进行查看的数组,我需要更新数组中的特定对象
modified_data(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log("modified_data fun", data);
// console.log(this.dailyDays);
var array = this.dailyDays;
for (var i = 0; i < array.length; i++) {
var element = array[i];
// console.log("in aloop",element.day);
if (element.day === data.day) {
console.log("got same da", element);
this.dailyDays.push({
day: data.day,
month: this.currentDate.getMonth(),
year: this.currentDate.getFullYear(),
price: data.price,
brand: data.selectedBrand,
howManyDay: data.selectedDay,
quantity: data.selectedQuantity
});
} else {
}
}
})
}
通过使用上面的代码,一个新对象在数组的底部以html,
添加如果我找到相同的日期,则视图中的数组会列出日期,然后应使用新对象更新该日期 有人帮助我
答案 0 :(得分:0)
据我所知,逻辑看起来应该是这样的。它在array
中查找现有对象,如果找到匹配项,则返回index
,如果没有,则返回-1
。基于此,您可以执行
modified_data(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log("modified_data fun", data);
// console.log(this.dailyDays);
// var array = this.dailyDays;
let updateItem = this.dailyDays.find(this.findIndexToUpdate, data.day);
let index = this.dailyDays.indexOf(updateItem);
if(index > -1){
// Add whatever logic you need to update existing object
// below line will replace the whole object
this.dailyDays[index] = data;
}
else{
this.dailyDays.push({
day: data.day,
month: this.currentDate.getMonth(),
year: this.currentDate.getFullYear(),
price: data.price,
brand: data.selectedBrand,
howManyDay: data.selectedDay,
quantity: data.selectedQuantity
})
}
})
findIndexToUpdate(data) {
return data.day === this;
}