繁体   English   中英

循环通过 object 并仅返回某些键及其值

[英]Loop through an object and only return certain keys together with their values

鉴于以下 object,我如何循环通过此 object 以获得键和值,但仅适用于以下键:

    "myName": "Demo"
    "active": "Y"
    "myCode": "123456789"
    "myType": 1


let a = {
    "values": {
        "myName": "Demo",
        "active": "Y",
        "myCode": "123456789",
        "myType": 1,
        "myGroups": [
            {
                "myGroupName": "Group 1",
                "myTypes": [
                    {
                        "myTypeName": "323232",
                        "myTypeId": "1"
                    }
                ]
            },
            {
                "myGroupName": "Group 2",
                "myTypes": [
                    {
                        "myTypeName": "523232",
                        "myTypeId": "2"
                    }
                ]
            }
        ]
    }
}

我努力了:

for (const [key, value] of Object.entries(a.values)) {
  console.log(`${key}: ${value}`);
For}

但这将返回所有键及其值。

您可以使用字典(数组)来包含要为其提取属性的键,然后使用Object.entries reduce值以生成仅匹配字典中included的条目的新 object。

 let a = { "values": { "myName": "Demo", "active": "Y", "myCode": "123456789", "myType": 1, "myGroups": [{ "myGroupName": "Group 1", "myTypes": [{ "myTypeName": "323232", "myTypeId": "1" }] }, { "myGroupName": "Group 2", "myTypes": [{ "myTypeName": "523232", "myTypeId": "2" }] } ] } } const arr = [ 'myName', 'active', 'myCode', 'myType' ]; const out = Object.entries(a.values).reduce((acc, [key, value]) => { if (arr.includes(key)) acc[key] = value; return acc; }, {}); console.log(out);

最好的答案是设置所需键的数组,然后迭代数组而不是原始对象条目的数组。 这就是您实现这一目标的方式:

 let a = { values: { myName: "Demo", active: "Y", myCode: "123456789", myType: 1, myGroups: [{ myGroupName: "Group 1", myTypes: [{ myTypeName: "323232", myTypeId: "1" }] }, { myGroupName: "Group 2", myTypes: [{ myTypeName: "523232", myTypeId: "2" }] }] } }; const keys = ['myName', 'active', 'myCode', 'myType']; const cherryPick = (obj, keys) => keys.reduce((a,c) => (a[c] = obj[c], a), {}); console.log(cherryPick(a.values, keys));

上面的示例适用于许多提供的键。 如果提供的 object 中不存在某个键,则其值将是未定义的。 如果您只想保留具有值的属性,只需向cherryPick() function 添加一个可选过滤器,如下所示:

 let test = { a: 1, b: 2 }; const keys = ['a', 'b', 'c']; const cherryPick = (obj, keys, filter = 0) => keys.filter(key => filter? obj[key]: 1).reduce((acc,key) => (acc[key] = obj[key], acc), {}); console.log('STORE undefined:: cherryPick(test, keys)', cherryPick(test, keys)); console.log('FILTER undefined:: cherryPick(test, keys, 1)', cherryPick(test, keys, true));
 /* Ignore this */.as-console-wrapper { min-height: 100%; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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