繁体   English   中英

从基于动态键数组的数组中返回值

[英]Return values from an array based on dynamic array of keys

我有一个键数组,我想迭代它们并返回它们对应的值。

一般来说,我知道,我可以做一个object.key_nameobject[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)

你几乎在那里:你只需要从键数组开始:

arr.map(key => data.map(o => o[key]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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