I have an array of keys and I want to iterate of them and return their corresponding values.
Generally, I know, I can just do a object.key_name
or object[key_name]
but I have a dynamic array and will populate with different keys.
Data:
data = [{hello: 'abc', asd: '123', fgh: '345' },
{hello: 'sdf', asd: '456', fgh: 'df' },
{hello: 'ty', asd: '789', fgh: '345675' },
{hello: 'qwe', asd: '123', fgh: '987' }]
array format: arr = ['asd', 'fgh']
I am trying to do: let x = data.map(o => arr.map(strs => o[strs]));
Result:
["123", "345"]
["456", "df"]
["789", "345675"]
["123", "987"]
Is there any way for me to get:
["123", "456", "789", "123"] <= array for asd
["345", "df", "345675", "987"] <= array for fgh
Change the order of your map calls - first iterate the format
array, and then extract the values from the data
:
const data = [{"hello":"abc","asd":"123","fgh":"345"},{"hello":"sdf","asd":"456","fgh":"df"},{"hello":"ty","asd":"789","fgh":"345675"},{"hello":"qwe","asd":"123","fgh":"987"}] const format = ['asd', 'fgh'] const result = format.map(f => data.map(o => o[f])) console.log(result)
You where almost there: You just need to start with the array of the keys:
arr.map(key => data.map(o => o[key]));
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.