查询返回集合中的对象数组。我想为该数组中的每个对象添加一个字段,并更新该数组的每个对象中的另一个字段。
更新前的产品数组:
[{ _id: 58d895b8ffc0346230a43a89,
event: 'Junior Girls 12s',
group: 'nonpro',
price: 50,
day: 'Friday' },
{ _id: 59d895b8ffc0346230a43a89,
event: 'Junior Girls 14s',
group: 'nonpro',
price: 50,
day: 'Friday', }]
我更新对象数组的代码:
//add the field and changed price if late fee applies
for(var i = 0; i < products.length; i++) {
products[i].field = registered.frifield;
console.log(products[i].field);
if(settings.latefeeamt > 0 && settings.frilatefee === true) {
products[i].price += settings.latefeeamt;
}
console.log(products[i]);
console.log(events.friday);
}
产品数组在更新后应该如何看待:
[{ _id: 58d895b8ffc0346230a43a89,
event: 'Junior Girls 12s',
group: 'nonpro',
price: 60,
day: 'Friday',
field: 'Main' },
{ _id: 59d895b8ffc0346230a43a89,
event: 'Junior Girls 14s',
group: 'nonpro',
price: 60,
day: 'Friday',
field: 'Main' }]
我怎样才能让它发挥作用?它console.logs循环中的正确字段,但是当它完成时我得到原始数组。
答案 0 :(得分:0)
答案 1 :(得分:0)
嗨,我不确定这部分代码,因为没有定义设置
if(settings.latefeeamt > 0 && settings.frilatefee === true) {
products[i].price += settings.latefeeamt;
}
在这里你有一个代码可以根据日期改变条件,你可以根据你的规范更新它希望它有帮助
var products = [{
_id: '58d895b8ffc0346230a43a89',
event: 'Junior Girls 12s',
group: 'nonpro',
price: 50,
day: 'Friday'
},
{
_id: '58d895b8ffc0346230a43a89',
event: 'Junior Girls 14s',
group: 'nonpro',
price: 50,
day: 'moday',
}];
console.log(products);
for(product of products) {
product.field = 'Main';
if (product.day === 'moday') {
product.price = 30;
}
}
console.log(products);