javascript覆盖添加到数组的先前元素

时间:2019-03-05 18:26:29

标签: javascript

当我推入数组时,它会覆盖最后添加的元素。

这是我的代码:

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

我得到的输出:

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

我想要的输出:

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您必须将obj.item声明为数组,而不是等于值,而应将它们压入数组

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

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

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

答案 2 :(得分:1)

使用 reduce 方法

const test = `result1
result2
result3`;

const res = test.split(/[\n\r]+/).map(aaa => (aaa)).reduce((all, acc) => {
  const [a] = all
  a.item.push({
    "result": acc
  })
  return all
}, [{
  name: [],
  item: []
}])

console.log(res)