将相同的 property:value 对添加到数组中的多个对象

Adding same property:value pair to multiple objects in array

我有两个数组,它们在结构上几乎相同,除了一个在每个对象上都有一个 property:value 对,而另一个没有。

纽卡斯尔阵列 (with clubCode 属性)

 [
            {"clubCode": "newcastle-united",
                "firstName": "Tim",
                "lastName": "Krul",
                "position": "gk"},

            {"clubCode": "newcastle-united",
                "firstName": "Rob",
                "lastName": "Elliot",
                "position": "gk"}
]

阿森纳阵列(clubCode属性)

 [
            {"firstName": "Petr",
                "lastName": "Cech",
                "position": "gk",

            {"firstName": "David",
                "lastName": "Ospina",
                "position": "gk"}
] 

是否可以 push() clubCode 属性 到 Arsenal 数组中的每个 对象,所以我不必手动将其添加到每一个?

...所以每个对象都以 "clubCode": "arsenal".

开头

或者如果有任何其他解决方案,我很想听听。

如有任何帮助,我们将不胜感激。提前致谢。

在此上下文中尝试使用 Array.prototype.map()

arsenalArray = arsenalArray.map(function(itm){
  return (itm.clubCode = "arsenal", itm);
});

DEMO

您可以在您的数据结构上使用 Array.prototype.forEach

var x =  [
            {"firstName": "Petr",
                "lastName": "Cech",
                "position": "gk",
            },
            {"firstName": "David",
                "lastName": "Ospina",
                "position": "gk"}
         ]; 

x.forEach(function(e){e.clubCode='arsenal';})
    $scope.ar1 = [
            {"clubCode": "newcastle-united",
                "firstName": "Tim",
                "lastName": "Krul",
                "position": "gk"},

            {"clubCode": "newcastle-united",
                "firstName": "Rob",
                "lastName": "Elliot",
                "position": "gk"}
];

    $scope.ar1.forEach(function (value) {
      value.clubCode = "newcastle-united";
    });

    console.log($scope.ar1);

使用起来非常简单 lodash.js

_.assign(arsenalArray, { clubCode: "arsenal" });