简体   繁体   中英

How to get value of keys present in a Json given that the keys are given in an array in Javascript?

Lets say I have an array consisting of keys present in a JSON,

const keys = ['Person:name','Person:Address:zip']

Assume the JSON is as below

let data = [
    {"Person":[
        {"name":"P1",
        "Address":{
            "zip":"01"}   
        },
        {"name":"P2",
        "Address":{
            "zip":"02"}
         }
        ]
    },
    {"Person":[
        {"Personname":"P3",
        "Address":{
            "zip":"03"}   
        },
        {"name":"P4",
        "Address":{
            "zipcode":"04"}
         }
        ]
    },
    {"People":[
        {"name":"P5",
        "Address":{
            "zip":"05"}   
        },
        {"name":"P6",
        "Address":{
            "zip":"06"}
         }
        ]
    },
]

Based on the keys array, I will have to traverse through the data dictionary to get its respective values. For the above example, the result should be like

[{"name":'P1','zip':'P1'},{"name":'P2','zip':'P2'},{"name":Null,'zip':'P3'},{"name":'P4','zip':Null}]

I have tried various methods such as recursion and nested loops in the Javascript to no vail to get these results. Can anyone please help regarding the same?

I'll re use a recent answer of mine. I ended up rewriting of course. Anyway, it's doable for one key-path, but it's unclear how to combine 2 or more. Here's a solution for 1 key-path.

 const keys = ['Person:name', 'Person:Address:zip'] let data = [{ "Person": [{ "name": "P1", "Address": { "zip": "01" } }, { "name": "P2", "Address": { "zip": "02" } } ] }, { "Person": [{ "Personname": "P3", "Address": { "zip": "03" } }, { "name": "P4", "Address": { "zipcode": "04" } } ] }, { "People": [{ "name": "P5", "Address": { "zip": "05" } }, { "name": "P6", "Address": { "zip": "06" } } ] }, ] function get_by_path(arr, arr_path) { var pointer = arr; var key = arr_path.shift(); while (arr_path.length) { var step = []; pointer.forEach(function(item) { step.push(item? (item[key]? item[key]: {}): {}) }); pointer = step.flat(); key = arr_path.shift(); } var result = pointer.map(function(item) { var obj = {} obj[key] = item? (item[key]? item[key]: null): null return obj }) return result; } keys.forEach(function(key) { var path = key.split(':'); var arr = get_by_path(data, path) console.log (arr); })
 .as-console-wrapper { max-height: 100%;important; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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