Jose the hose
Jose the hose

Reputation: 1895

Push object properties in an array into another array of objects

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

Answers (2)

Ele
Ele

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

brunnerh
brunnerh

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

Related Questions