brxnzaz
brxnzaz

Reputation: 491

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" }
    ]
  }
]

Upvotes: 0

Views: 77

Answers (3)

Geeky
Geeky

Reputation: 7496

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

Upvotes: 2

Aziz.G
Aziz.G

Reputation: 3721

Using reduce method

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)

Upvotes: 1

ellipsis
ellipsis

Reputation: 12152

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(/[\n\r]+/).map(aaa => (aaa));

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

Upvotes: 1

Related Questions