将键值对添加到数组中的特定对象

Adding key value pair to specific objects in an array

我有一个对象数组,如下所示:

[{headerName: "Test 1", field: "Test 1", type_id: 1}, {headerName: "Test 2", field: "Test 2", type_id: 2}, {headerName: "Test 3", field: "Test 3", type_id: 3}, {headerName: "Name", field: "Name", type_id: 3}, {headerName: "Income", field: "Income", type_id: 2}]

这只是数组的一个基本示例,因为它可以是任意长度的。基本上我需要做的是当 type_id 为 3 时,我需要向数组中的那些对象添加一个额外的 key/value 对。

我该怎么做?

如有任何帮助,我们将不胜感激。

感谢您的宝贵时间。

更新:

Key/value 我要添加的对是:cellRenderer: customEditor

一个es6解决方案

yourArray = yourArray.map( obj => {
    if( obj.type_id === 3 ){
      return { ...obj, cellRenderer: customEditor };
    }
    return obj;
}

一个es5解决方案

yourArray = yourArray.map( function( obj ){
    if( obj.type_id === 3 ){
      Object.defineProperty(obj, "cellRenderer", { value : customEditor })
    }
    return obj;
}

使用Array.mapObject.keys函数的解决方案:

var arr = [{headerName: "Test 1", field: "Test 1", type_id: 1}, {headerName: "Test 2", field: "Test 2", type_id: 2}, {headerName: "Test 3", field: "Test 3", type_id: 3}, {headerName: "Name", field: "Name", type_id: 3}, {headerName: "Income", field: "Income", type_id: 2}],
    extraObj = {'cellRenderer': 'customEditor'};

arr.map(function(obj){
   if (obj['type_id'] === 3) {
       Object.keys(this).forEach((k) => obj[k] = this[k]);
   }
}, extraObj);

console.log(JSON.stringify(arr, 0, 4));

输出:

[
    {
        "headerName": "Test 1",
        "field": "Test 1",
        "type_id": 1
    },
    {
        "headerName": "Test 2",
        "field": "Test 2",
        "type_id": 2
    },
    {
        "headerName": "Test 3",
        "field": "Test 3",
        "type_id": 3,
        "cellRenderer": "customEditor"
    },
    {
        "headerName": "Name",
        "field": "Name",
        "type_id": 3,
        "cellRenderer": "customEditor"
    },
    {
        "headerName": "Income",
        "field": "Income",
        "type_id": 2
    }
]

另一个组合 map and Object.assign

var data = [{headerName: "Test 1", field: "Test 1", type_id: 1}, {headerName: "Test 2", field: "Test 2", type_id: 2}, {headerName: "Test 3", field: "Test 3", type_id: 3}, {headerName: "Name", field: "Name", type_id: 3}, {headerName: "Income", field: "Income", type_id: 2}];

var extend = { cellRenderer: 'customEditor' }

data = data.map( item => {
  if( item.type_id == 3 ){
    return Object.assign( item, extend );
  }
  return item;
});