gpt4 book ai didi

Javascript 对象不附加新属性

转载 作者:可可西里 更新时间:2023-11-01 10:08:48 25 4
gpt4 key购买 nike

我有这个函数,我在其中检索一个对象数组,然后我有一个 for 循环来遍历对象,并向它附加一个索引或 ind 属性:

module.exports.getCustomers = async (req, res) => {
let customers = await Customers.find({}, { "_id": 1 });

for (var i = 0; i < customers.length; i++) {
customers[i].ind = i;
}

console.log(customers)
}

但是当我运行它时,数据返回为

[
{ _id: ... },
{ _id: ... },
...
]

代替:

[
{_id: ..., ind: 0},
{_id: ..., ind: 1},
...
]

请问我该如何解决

最佳答案

更改您的 for 并将其转换为 map

module.exports.getCustomers = async (req, res) => {
let customers = await Customers.find({}, { "_id": 1 });

let mappedCustomers = customers.map((customer, index) => {
customer['ind'] = index;
return customer;
});


console.log(mappedCustomers);
return mappedCustomers;
}

或者代替返回客户,您可以创建一个全新的客户。

let mappedCustomers = customers.map((customer, index) => {
return {...customer, ind: index};
});

关于Javascript 对象不附加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com