繁体   English   中英

遍历数组,将每个项目添加到对象中,然后将其推入Javascript中的数组

[英]Loop through an Array, add each item to an object and push it to an array in Javascript

我有一个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循环确认正确迭代。 最终输出只有一个值。

当前,您只有一个用于format变量-您只将一项推入数组,只是对其进行了多次变异,导致数组包含对同一对象的3个引用。

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

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

虽然答案说明了您的代码问题。 这是我解决相同问题的方法。

const input = [121, 432, 322];
Array.from(input, brand_id => ({ term: { brand_id }}))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM