将数组中的对象属性推送到另一个对象数组中

时间:2018-03-23 19:49:39

标签: javascript typescript ecmascript-6

我试图找出如何从一个数组中取出对象并将它们合并到另一个对象数组的对象中。我在 angular 5 应用程序中使用 Typescript

数组1:

[
  {
    "outcomeId": 1,
    "outcomeName": "draw",
    "stake": 100
  },
  {
    "outcomeId": 12,
    "outcomeName": "Gandzasar Kapan FC 2",
    "stake": 100000000
  }
]

数组2:

[
  {
    "success": true
  },
  {
    "success": false,
    "error": {
        "description": "Insufficient balance 989066"
       }
    }
 ]

结果数组:

[
  {
    "outcomeId": 9171077,
    "outcomeName": "draw",
    "stake": 100,
    "success": true
  },
  {
    "outcomeId": 9171076,
    "outcomeName": "Gandzasar Kapan FC 2",
    "stake": 100000000,
    "success": false,
    "error": {
      "description": "Insufficient balance 989066"
    }
  }
]

我知道如何使用 .map 来循环遍历数组,但我不知道如何用两个来完成它然后合并它们。

2 个答案:

答案 0 :(得分:3)

这样的事情:

array1.map((element, index) => ({ ...element, ...array2[index]}));

这会通过将当前元素的属性和该索引中相应元素的属性扩展到另一个数组中来创建新对象。

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);

答案 1 :(得分:3)

这种方法将创建一个新数组,新数组和旧数组将引用一些对象。

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; }

没有Spread语法,使用函数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; }