简体   繁体   中英

Adding key value pair to specific objects in an array

I have an array of objects that looks like this:

[{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}]

This is just a basic example of what the array might look like as it can be of any length. Basically what I need to do is when the type_id is 3 I need to add an extra key/value pair to those objects in the array.

How would I go about doing this?

Any help would be much appreciated.

Thanks for your time.

UPDATE:

Key/value pair I am trying to add is : cellRenderer: customEditor

An es6 solution

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

An es5 solution

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

The solution using Array.map and Object.keys functions:

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

The output:

[
    {
        "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
    }
]

Another take combining 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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM