首页 > 解决方案 > javascript overwrite previous element added to array

问题描述

When i push into my array, it overwrite the last element added.

Here is my code:

const array = [{ name: [] }];

const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));

array.forEach((obj) => {
  ways.forEach((element) => {
    obj.item = [{ result: element }];
  });
});

The output i get :

[ 
  { 
    "name": [], 
    "item": [{ "result": "result3" }] 
  }
]

The output i want :

[
  {
    "name": [],
    "item": [
      { "result": "result1" },
      { "result": "result2" },
      { "result": "result3" }
    ]
  }
]

标签: javascript

解决方案


const array = [{ name: [] }];

const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));

array.map((obj) => {
obj.item = [];
  ways.map((element) => {
    obj.item .push([{ result: element }]);
  });
});

console.log(array);


推荐阅读