简体   繁体   中英

Get key names from map of objects

I have a dynamic map of objects like this:

let specs = {source1:[{key1:value2, key2:value2, key3:value3}, {key1:value4, key2:value5, key3:value6}]
             source2:[{key4:value7, key5:value8, key6:value9}, {key4:value10, key5:value11, key6:value12}]

Key names (key1, key2 ...) vary. I am looking for a way to extract key names for each source. I want output like this:

source1_keys ={key1, key2, kye3}
source2_kyes = {key4, key5, key6}

You can use map() and get all the values of the first object in each array using Object.keys

Note: Below method will only get the keys of the first object inside each array.

 let specs = {source1:[{key1:'value2', key2:'value2', key3:'value3'}, {key1:'value4', key2:'value5', key3:'value6'}], source2:[{key4:'value7', key5:'value8', key6:'value9'}, {key4:'value10', key5:'value11', key6:'value12'}]}; const keys = Object.fromEntries( Object.entries(specs) .map(([k, v]) => [k, Object.keys(v[0])]) ); console.log(keys)

If you want to get all the unique keys from each element of the array then use the below method

 let specs = {source1:[{key1:'value2', key2:'value2', key3:'value3'}, {key1:'value4', extra1:'value5', key3:'value6'}], source2:[{key4:'value7', key5:'value8', key6:'value9'}, {key4:'value10', extra2:'value11', key6:'value12'}]}; const keys = Object.fromEntries( Object.entries(specs) .map(([k, v]) => [k, [...new Set(v.flatMap(x => Object.keys(x)))]]) ); console.log(keys)

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