0

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" }
    ]
  }
]
3
  • just define obj.item as array and push values to it Commented Mar 5, 2019 at 18:30
  • You aren't pushing anything into an array. Commented Mar 5, 2019 at 18:31
  • Some sidenotes: what is the map for? You take each value of the array that split creates and replace it with itself. And why would you want to iterate over the ways-array? You basically have an array that you want to store, as an array, in another variable. So you iterate over it and copy each value by hand. I assume you want to create a deep copy of the ways-array; I'd recommend using some built-in solution like Array.from(ways) to achieve this. Commented Mar 5, 2019 at 18:45

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.