Skip to content
Advertisement

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(/[nr]+/).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" }
    ]
  }
]

Advertisement

Answer

You have to declare obj.item as an array and instead of equating values you should push them in the array

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

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

array.forEach((obj) => {
  obj.item = [];
  ways.forEach((element) => {
    obj.item.push({
      result: element
    });
  });
});
console.log(array)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement