我有一个键数组,我想迭代它们并返回它们相应的值。
一般来说,我知道,我可以只执行 object.key_name
或 object[key_name]
但我有一个动态数组,并且会填充不同的键。
数据:
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' }]
数组格式:arr = ['asd', 'fgh']
我正在尝试这样做:let x = data.map(o => arr.map(strs => o[strs]));
结果:
["123", "345"]
["456", "df"]
["789", "345675"]
["123", "987"]
我有什么办法可以得到:
["123", "456", "789", "123"] <= array for asd
["345", "df", "345675", "987"] <= array for fgh
最佳答案
更改 map 调用的顺序 - 首先迭代 format
数组,然后从 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)
关于javascript - 根据动态键数组从数组返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61330844/