如果使用lodash在另一个对象中存在属性,则向对象添加属性 [英] Add propertie to object if property exists in another object using lodash

查看:1245
本文介绍了如果使用lodash在另一个对象中存在属性,则向对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象,我需要根据另一个对象的属性将属性添加到一个对象:

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'
                },
            },.....
        ]

我想添加:

"visible":false,
"type": 'hidden',

tableCols对象,其中data属性与dependsOn中的属性匹配.

to tableCols object where data property matches the property in dependsOn.

https://jsfiddle.net/zwpu70no/3/

推荐答案

使用Object.keysArray.indexOf函数的解决方案:

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

'tableCols'数组中单个对象的输出示例:

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

这篇关于如果使用lodash在另一个对象中存在属性,则向对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆