【问题标题】:Loop through an Array, add each item to an object and push it to an array in Javascript遍历一个数组,将每个项目添加到一个对象并将其推送到 Javascript 中的数组
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    虽然this 回答解释了您的代码问题。这是我解决同样问题的方法。

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

    【讨论】:

    • 有什么理由使用这个而不是另一个?还是根据经验来决定使用哪个来做什么?据我了解,Array.map 是一个类似于Array.foreach 等的功能,但更高效。而Array.from 是一种从现有数组/类数组对象创建另一个数组的方法。
    • Yes.. Array.from 是一种使用映射函数 brand_id => ({ term: { brand_id }}) 从现有数组/类数组对象创建另一个数组的方法。
    • @esafwan Read this answer Array.from 用法的最佳示例是 here
    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多