循环遍历数组,将每个项添加到对象并将其推送到Javascript中的数组

esa*_*wan 3 javascript arrays json object node.js

我有一个ID的数组如下:

[121, 432, 322]
Run Code Online (Sandbox Code Playgroud)

我希望以下列格式将所有内容添加到数组中(预期输出):

[
    {
        "term": {
            "brand_id": 121
        }
    },
    {
        "term": {
            "brand_id": 432
        }
    },
    {
        "term": {
            "brand_id": 322
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

我能够正确地获得结构并获得几乎所有的结果.但最终只有最后一个值作为对象的所有项目中的值如下(当前输出):

[
        {
            "term": {
                "brand_id": 322
            }
        },
        {
            "term": {
                "brand_id": 322
            }
        },
        {
            "term": {
                "brand_id": 322
            }
        }
    ]
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

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);

});
Run Code Online (Sandbox Code Playgroud)

虽然console.log在循环中确认正在迭代.最终输出只有一个值.

Cer*_*nce 8

你目前只有一个变量format- 你只是将一个项目推送到数组,你只是多次改变它,导致数组包含对同一个对象的3个引用.

format改为在每次迭代时创建..map.forEach将一个数组转换为另一个数组更合适:

const input = [121, 432, 322];
console.log(
  input.map(brand_id => ({ term: { brand_id }}))
);
Run Code Online (Sandbox Code Playgroud)