[英]Loop through an Array, add each item to an object and push it to an array in Javascript
I have an array of ID's as below: 我有一个ID数组,如下所示:
[121, 432, 322]
I want all of it to be added to an array in the following format (Expected Output) : 我希望将其全部以以下格式(预期输出)添加到数组中:
[
{
"term": {
"brand_id": 121
}
},
{
"term": {
"brand_id": 432
}
},
{
"term": {
"brand_id": 322
}
}
]
I am able to get the structure right and get a result almost as expected. 我能够正确地构造结构并获得几乎预期的结果。 But am ending up having just the last value as the value in all items of the object as below (Current Output) : 但是最终将最后一个值作为对象的所有项中的值,如下所示(当前输出) :
[
{
"term": {
"brand_id": 322
}
},
{
"term": {
"brand_id": 322
}
},
{
"term": {
"brand_id": 322
}
}
]
My code is as below: 我的代码如下:
The array of IDs is in an array named brands. 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);
});
Though console.log
in loop confirms am iterating correctly. 尽管console.log
in循环确认正确迭代。 The final output just has one value. 最终输出只有一个值。
You currently only have one variable for format
- you're only ever pushing one item to the array, you're just mutating it multiple times, resulting in the array containing 3 references to the same object. 当前,您只有一个用于format
变量-您只将一项推入数组,只是对其进行了多次变异,导致数组包含对同一对象的3个引用。
Create the format
on each iteration instead. 而是在每次迭代时创建format
。 .map
is more appropriate than .forEach
when transforming one array into another: 当将一个数组转换为另一个数组时, .map
比.forEach
更合适:
const input = [121, 432, 322]; console.log( input.map(brand_id => ({ term: { brand_id }})) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.