Reputation: 491
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
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
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
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