将键值对添加到数组

时间:2016-05-20 09:07:10

标签: arrays object reactjs ag-grid

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

[{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时我需要为数组中的那些对象添加额外的键/值对。

我将如何做到这一点?

非常感谢任何帮助。

感谢您的时间。

更新:

我要添加的键/值对是:cellRenderer: customEditor

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

使用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
    }
]

答案 2 :(得分:1)

结合mapObject.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;
});