遍历数组,将每个项目添加到对象中,然后将其推入Javascript中的数组 [英] Loop through an Array, add each item to an object and push it to an array in Javascript

查看:932
本文介绍了遍历数组,将每个项目添加到对象中,然后将其推入Javascript中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID数组,如下所示:

I have an array of ID's as below:

[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
            }
        }
    ]

我的代码如下:

ID数组位于名为brands的数组中.

The array of IDs is in an array named 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确认正确迭代.最终输出只有一个值.

Though console.log in loop confirms am iterating correctly. The final output just has one value.

推荐答案

您目前仅对format使用一个变量-您只将一项推入数组,只是对其进行了多次变异,结果包含3个对同一对象的引用的数组中.

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.将一个数组转换为另一个数组时,.map.forEach更合适:

Create the format on each iteration instead. .map is more appropriate than .forEach when transforming one array into another:

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

这篇关于遍历数组,将每个项目添加到对象中,然后将其推入Javascript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆