问题很简单。我尝试了很多次,因此在stackoverflow中寻求帮助。 我有一个名为data的对象数组,它是从mongodb数据库返回的数据。 格式类似于:
let data = [
{ booking: [ ref], max_booking: 0 },
{ booking: [ref], max_booking: 3 },
{ booking: [ref], max_booking: 5 },
{booking: [ref], max_booking: 4}
];
根据请求,我添加了来自数据库的真实数据:
[ { booking: [],
_id: null,
__v: 0,
comment: 'this is a comment',
date: 2020-07-26T00:00:00.000Z,
event_detail: 'this is event detail',
location: 'Kthm',
max_booking: 5,
meal_option: [ [Object] ],
sponsor_address: 'xxxx',
sponsor_name: 'yyyy',
id: null },
{ booking: [],
_id: 5ef60fab6c164281aee9ae2e,
date: 2020-07-30T00:00:00.000Z,
location: 'Kthm',
comment: 'this is another',
sponsor_name: 'Micorosft',
sponsor_address: 'USA',
event_detail: 'this is event detail',
meal_option: [ [Object] ],
max_booking: 5,
__v: 0,
id: '5ef60fab6c164281aee9ae2e' },
{ booking: [],
_id: 5ef6131f6c164281aee9ae30,
date: 2020-07-30T00:00:00.000Z,
location: 'TAN TOCK SENG HOSPITAL',
comment: 'this is dsadasdas',
sponsor_name: 'Asus',
sponsor_address: 'Los Angeles, USAssadsad',
event_detail: 'this is event detail',
meal_option: [ [Object] ],
max_booking: 5,
__v: 0,
id: '5ef6131f6c164281aee9ae30' },
]
我想执行如下操作: 当max_booking与任何对象上的预订数组的长度匹配时,应像该对象一样向该特定对象添加一个新元素。
{booking:[lets assume 5], max_booking: 5, result:1}
如果预订仍少于预定数量,则应添加一个新元素,但结果为0,如
{booking:[lets asssume 3], max_booking:5, result:0}
要执行此操作,我做了:
data.map((d, i) => {
if (d.booking.length === d.max_booking) {
console.log("Fully Booked in index", i);
d.result = 1;
} else {
console.log("Not booked");
d.result = 0;
}
console.log(d.result);
});
console.log(data[3]);
现在让我们忽略其他应该小于符号。 foreach循环中d.result的值打印在控制台上,但是当我记录数据时,什么都没有改变。 谁能帮助我。预先感谢。
答案 0 :(得分:0)
为什么人们会放弃简单的for循环?
for(var i=0;i<data.length;i++) {
if (data[i].booking.length === data[i].max_booking) {
console.log("Fully Booked in index", i);
data[i].result = 1;
} else {
console.log("Not booked");
data[i].result = 0;
}
}
console.log(data.result);
答案 1 :(得分:0)
由于map()return a new array,如果您更改map()中的数据,则应像这样返回新数组:
var data = [{a:1},{a:2}]
data = data.map((d,i)=>{d.a = d.a+1; return d})
// Array [2]
// 0: Object { a: 2 }
// 1: Object { a: 3 }
答案 2 :(得分:0)
您似乎忘记了从地图内部返回d
。您必须从map
回调返回以获取新数组。
const data = [
{ booking: [], max_booking: 0 },
{ booking: [{}, {}, {}], max_booking: 3 },
{ booking: [], max_booking: 5 },
{ booking: [{}, {}, {}], max_booking: 4 },
]
const mapped = data.map((d, i) => {
if (d.booking.length === d.max_booking) {
console.log("Fully Booked in index", i);
d.result = 1;
} else {
console.log("Not booked");
d.result = 0;
}
console.log(d.result);
return d
})
console.log(mapped)