When i push into my array, it overwrite the last element added.
Here is my code:
JavaScript
x
13
13
1
const array = [{ name: [] }];
2
3
const test = `result1
4
result2
5
result3`;
6
const ways = test.split(/[nr]+/).map(aaa => (aaa));
7
8
array.forEach((obj) => {
9
ways.forEach((element) => {
10
obj.item = [{ result: element }];
11
});
12
});
13
The output i get :
JavaScript
1
7
1
[
2
{
3
"name": [],
4
"item": [{ "result": "result3" }]
5
}
6
]
7
The output i want :
JavaScript
1
11
11
1
[
2
{
3
"name": [],
4
"item": [
5
{ "result": "result1" },
6
{ "result": "result2" },
7
{ "result": "result3" }
8
]
9
}
10
]
11
Advertisement
Answer
You have to declare obj.item as an array and instead of equating values you should push them in the array
JavaScript
1
18
18
1
const array = [{
2
name: []
3
}];
4
5
const test = `result1
6
result2
7
result3`;
8
const ways = test.split(/[nr]+/).map(aaa => (aaa));
9
10
array.forEach((obj) => {
11
obj.item = [];
12
ways.forEach((element) => {
13
obj.item.push({
14
result: element
15
});
16
});
17
});
18
console.log(array)