【发布时间】:2019-01-19 13:42:53
【问题描述】:
我有一个 ID 数组,如下所示:
[121, 432, 322]
我希望将其全部添加到以下格式的数组中(预期输出):
[
{
"term": {
"brand_id": 121
}
},
{
"term": {
"brand_id": 432
}
},
{
"term": {
"brand_id": 322
}
}
]
我能够得到正确的结构并得到几乎符合预期的结果。但最终只有最后一个值作为对象所有项目中的值,如下所示(当前输出):
[
{
"term": {
"brand_id": 322
}
},
{
"term": {
"brand_id": 322
}
},
{
"term": {
"brand_id": 322
}
}
]
我的代码如下:
ID 数组位于名为brands 的数组中。
let brands_formated = [];
//I have the array stored in `brands`
let format = { "term" : {
"brand_id": 0 //will be replaced
}
};
brands.forEach(function(brand) {
//The structure for brand query
format.term.brand_id = brand;
//Check if the right brand is format. Outputs as desired.
console.log(format);
brands_formated.push(format);
});
虽然console.log in loop 确认迭代正确。最终输出只有一个值。
【问题讨论】:
-
你将相同的对象引用推送到数组。
标签: javascript arrays json node.js object