我正在尝试用数组中的新对象替换一些现有对象,我有2个数组allDays
和storedDay
,两者将具有不同的大小allDays将有10个对象,storedDays将有4个对象但两者都具有相同的值day
mode(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log(data)
var allDay = this.dailyDays;
for (var i = 0; i < allDay.length; i++) {
var element = allDay[i];
var storedDay = data[i];
console.log("all Day",element.day);
console.log("stored Day",storedDay.day);
if (element.day === storedDay.day) {
console.log("we have same day", i)
data=({
day: data.day,
month: data.month,
year: data.year,
quantity: data.selectedQuantity,
brand: data.selectedBrand,
price: data.price,
})
// below line will replace the whole object
this.dailyDays[i] = data;
}
}
console.log(data.day)
})
}
在执行上述操作时我收到存储值错误,有人可以举例说明如何检查两个数组并使用storedDay
更新数组。
答案 0 :(得分:3)
您必须定义新变量以存储相同的日期值:
mode(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log(data);
var sameDay = null; // =======> define this variable
var allDay = this.dailyDays;
for (var i = 0; i < allDay.length; i++) {
var element = allDay[i];
var storedDay = data[i];
console.log("all Day",element.day);
console.log("stored Day",storedDay.day);
if (element.day === storedDay.day) {
console.log("we have same day", i)
sameDay=({ // ==========> change this
day: data.day,
month: data.month,
year: data.year,
quantity: data.selectedQuantity,
brand: data.selectedBrand,
price: data.price,
})
// below line will replace the whole object
this.dailyDays[i] = sameDay; // ======> change this
}
}
if(sameDay)
console.log(sameDay.day) // =======> and change this
})
}
答案 1 :(得分:0)
我设法找到了符合我要求的解决方案
mode(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log(data)
var sameDay;
var allDay = this.dailyDays;
for (var i = 0; i < allDay.length; i++) {
var allDayelement = allDay[i];
console.log("all Day",allDayelement.day);
data.forEach(forEachElement => {
console.log("forEachElement",forEachElement.day);
if (allDayelement.day === forEachElement.day) {
console.log("we have same day", i)
sameDay=({
day: forEachElement.day,
month: forEachElement.month,
year: forEachElement.year,
quantity: forEachElement.selectedQuantity,
brand: forEachElement.selectedBrand,
price: forEachElement.price,
})
// below line will replace the whole object
this.dailyDays[i] = sameDay;
}
});
}
// console.log(data.day)
})
}