[英]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. 基本上我需要做的是当type_id为3时,我需要向数组中的那些对象添加一个额外的键/值对。
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
我想添加的键/值对是: cellRenderer: customEditor
An es6 solution ES6解决方案
yourArray = yourArray.map( obj => {
if( obj.type_id === 3 ){
return { ...obj, cellRenderer: customEditor };
}
return obj;
}
An es5 solution ES5解决方案
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: 使用Array.map
和Object.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));
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 结合map和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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.