簡體   English   中英

如何在JavaScript中獲取數組中對象的所有鍵

[英]How to get all the keys of objects in an array in JavaScript

我想知道哪種更好的方法將數組中對象的所有鍵和值提取為單獨的數組。 我的方法要求我在通過映射到數組上提取對象的鍵和值之后,將數組弄平。

輸入項

const input = [{{a“:1,” b“:2},{” c“:3},{” d“:4},{},{” e“:null,” f“:6, “ g”:7}];

輸出量

const鍵= [“ a”,“ b”,“ c”,“ d”,“ e”,“ f”,“ g”];

const值= [1、2、3、4,null,6、7];

我的解決方案

 const input = [{ "a": 1, "b": 2 }, { "c": 3 }, { "d": 4 }, {}, { "e": null, "f": 6, "g": 7 }]; const keys = input.map(obj => [].concat(Object.keys(obj))).flat(); console.log(keys); const values = input.map(obj => [].concat(Object.values(obj))).flat(); console.log(values); 

您可以使用已實現的flatMap

flatMap()方法首先使用映射函數映射每個元素,然后將結果展平為新數組。 它與后跟深度為1的flat()的map()相同,但是flatMap()通常非常有用,因為將兩者合並為一種方法效率更高。

 const input = [{ "a": 1, "b": 2 }, { "c": 3 }, { "d": 4 }, {}, { "e": null, "f": 6, "g": 7 }]; const keys = input.flatMap(Object.keys); const values = input.flatMap(Object.values); console.log(keys,values) 

嘗試一個reduce函數,這樣就不必執行兩個循環,而只能在一個循環中完成所有操作?

 const input = [{ "a": 1, "b": 2 }, { "c": 3 }, { "d": 4 }, {}, { "e": null, "f": 6, "g": 7 }]; const { keys, values } = input.reduce((accum, obj) => ({ keys: [...accum.keys, ...Object.keys(obj)], values: [...accum.values, ...Object.values(obj)], }), { keys: [], values: [] }); console.log(keys, values) 

您可以獲取密鑰,然后展開一個數組:

 const input = [ { "a": 1, "b": 2 }, { "c": 3 }, { "d": 4 }, {}, { "e": null, "f": 6, "g": 7 } ]; const keys = input.map(a=> Object.keys(a)).flat(); const values = input.map(a=> Object.values(a)).flat(); console.log(keys) console.log(values) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM