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

前端 未结 2 1214
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 12:03

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 Outpu

相关标签:
2条回答
  • 2021-01-20 12:27

    While this answer explained the problem of your code. Here is my way to solve the same problem.

    const input = [121, 432, 322];
    Array.from(input, brand_id => ({ term: { brand_id }}))
    
    0 讨论(0)
  • 2021-01-20 12:34

    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.

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

    0 讨论(0)
提交回复
热议问题