簡體   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