问题
I have two objects and I need to add properties to one object based on match from properties of another:
var dependsOn= {
qTableIdent: {
//External object key mapping( object key : external key)
'RHID': 'RHID',
'CD_AGREGADO': 'NOME'
}
},
var tableCols= [
{
"targets": 1,
"title": 'RHID',
"label": 'RHID',
"data": 'RHID',
"name": 'RHID',
"width": "5%",
"filter": true,
"defaultContent": "",
"visible":false,
"type": 'hidden', //ADD this to properties
attr: {
'name': 'rhid'
},
},.....
]
I would like to add:
"visible":false,
"type": 'hidden',
to tableCols object where data property matches the property in dependsOn.
https://jsfiddle.net/zwpu70no/3/
回答1:
The solution using Object.keys and Array.indexOf functions:
var dependsOn = {
qTableIdent: {'RHID': 'RHID', 'SEQ': 'NOME'},
qTableDocs: {'RHID': 'RHID', 'DOC': 'DOC2'}
},
tableCols = [
{
"targets": 1,
"title": 'RHID',
"label": 'RHID',
"data": 'RHID',
"name": 'RHID',
"width": "5%",
"filter": true,
"defaultContent": "",
attr: {'name': 'rhid'}
}
],
newProps = {"visible": false, "type": 'hidden'}, // new properties to insert
dataKeys = [];
Object.keys(dependsOn).forEach(function(k) {
Object.keys(dependsOn[k]).forEach(function(key) {
if (dataKeys.indexOf(key) === -1) {
dataKeys.push(key);
}
});
});
// dataKeys now contains unique keys list: ["RHID", "SEQ", "DOC"]
tableCols.forEach(function(obj) {
if (dataKeys.indexOf(obj['data']) !== -1) {
Object.keys(this).forEach((k) => obj[k] = this[k]);
}
}, newProps);
console.log(JSON.stringify(tableCols, 0, 4));
console.log(JSON.stringify(tableCols, 0 , 4));
The output example for a single object inside 'tableCols' array:
[
{
"targets": 1,
"title": "RHID",
"label": "RHID",
"data": "RHID",
"name": "RHID",
"width": "5%",
"filter": true,
"defaultContent": "",
"attr": {
"name": "rhid"
},
"visible": false,
"type": "hidden"
}
]
来源:https://stackoverflow.com/questions/37296915/add-propertie-to-object-if-property-exists-in-another-object-using-lodash