Add Propertie To Object If Property Exists In Another Object Using Lodash
I have two objects and I need to add properties to one object based on match from properties of another: var dependsOn= { qTableIdent: { //Exter
Solution 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"}]
Post a Comment for "Add Propertie To Object If Property Exists In Another Object Using Lodash"