Reputation: 1895
I'm trying to figure out how to take objects from one array and merge them into objects of another array of objects. I'm using Typescript in an angular 5 application.
Array 1:
[
{
"outcomeId": 1,
"outcomeName": "draw",
"stake": 100
},
{
"outcomeId": 12,
"outcomeName": "Gandzasar Kapan FC 2",
"stake": 100000000
}
]
Array 2:
[
{
"success": true
},
{
"success": false,
"error": {
"description": "Insufficient balance 989066"
}
}
]
Result array:
[
{
"outcomeId": 9171077,
"outcomeName": "draw",
"stake": 100,
"success": true
},
{
"outcomeId": 9171076,
"outcomeName": "Gandzasar Kapan FC 2",
"stake": 100000000,
"success": false,
"error": {
"description": "Insufficient balance 989066"
}
}
]
I know how to use .map to loop over an array, but I have no idea how to do it with two and then merge them.
Upvotes: 0
Views: 123
Reputation: 33726
This approach will create a new array and some objects will be referenced by the new array and the older one.
var array1 = [{ "outcomeId": 1, "outcomeName": "draw", "stake": 100 }, { "outcomeId": 12, "outcomeName": "Gandzasar Kapan FC 2", "stake": 100000000 }];
var array2 = [{ "success": true }, { "success": false, "error": { "description": "Insufficient balance 989066" } }]
var result = array1.map((o, i) => ({...o, ...array2[i]}))
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Without Spread syntax, using the function Object.assign
var array1 = [{ "outcomeId": 1, "outcomeName": "draw", "stake": 100 }, { "outcomeId": 12, "outcomeName": "Gandzasar Kapan FC 2", "stake": 100000000 }];
var array2 = [{ "success": true }, { "success": false, "error": { "description": "Insufficient balance 989066" } }]
var result = array1.map((o, i) => Object.assign(o, array2[i]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3
Reputation: 184386
Something like this:
array1.map((element, index) => ({ ...element, ...array2[index]}));
This creates new objects by spreading the properties of the current element and those of the respective element at that index in the other array.
const array1 = [
{
"outcomeId": 1,
"outcomeName": "draw",
"stake": 100
},
{
"outcomeId": 12,
"outcomeName": "Gandzasar Kapan FC 2",
"stake": 100000000
}
]
const array2 =
[
{
"success": true
},
{
"success": false,
"error": {
"description": "Insufficient balance 989066"
}
}
]
const result = array1.map((element, index) => ({ ...element, ...array2[index]}));
console.log(result);
Upvotes: 3