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" }
]
}
]
obj.itemas array and push values to itmapfor? You take each value of the array thatsplitcreates and replace it with itself. And why would you want to iterate over theways-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 theways-array; I'd recommend using some built-in solution likeArray.from(ways)to achieve this.