简体   繁体   English

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

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

Given the following object, how can I loop through this object inorder to obtain both keys and values but only for the following keys:鉴于以下 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"
                    }
                ]
            }
        ]
    }
}

I have tried:我努力了:

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

but this will return all keys with their values.但这将返回所有键及其值。

You can use a dictionary (array) to contain the keys you want to extract the properties for, and then reduce over the values with Object.entries to produce a new object matching only those entries included in the dictionary.您可以使用字典(数组)来包含要为其提取属性的键,然后使用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);

The best answer would be to set up an array of the desired keys and then iterate over that array instead of an array of the original object's entries.最好的答案是设置所需键的数组,然后迭代数组而不是原始对象条目的数组。 This is how you would achieve that:这就是您实现这一目标的方式:

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

The above example will work for many provided keys.上面的示例适用于许多提供的键。 If a key does not exist in the supplied object, its value will be undefined.如果提供的 object 中不存在某个键,则其值将是未定义的。 If you want to only keep properties which have values, simply add an optional filter to the cherryPick() function, like this:如果您只想保留具有值的属性,只需向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