我有這個數組的數組獲取密鑰的陣列,陣列中的每個對象只有一個關鍵:JavaScript從對象
[{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]
我想所有鍵提取到一個數組,使得結果我要的是:
["hello", "there", "everybody"]
是什麼在Lodash或香草的JavaScript(最好ES6)這樣做的簡潔的方式?
我有這個數組的數組獲取密鑰的陣列,陣列中的每個對象只有一個關鍵:JavaScript從對象
[{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]
我想所有鍵提取到一個數組,使得結果我要的是:
["hello", "there", "everybody"]
是什麼在Lodash或香草的JavaScript(最好ES6)這樣做的簡潔的方式?
結合使用Object#assign單個對象,並使用Object#keys檢索對象的鍵:
const arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
const keys = Object.keys(Object.assign({}, ...arr));
console.log(keys);
而且使用lodash年代ES5版本_.assign()
與_.spread()
合併到單個對象,並_.keys()
領取鑰匙:
var arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
var keys = _.keys(_.spread(_.assign)(arr))
console.log(keys);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
您可以使用Array#map
以及Object.keys
。
let arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
let keys = [].concat(...arr.map(Object.keys));
console.log(keys);
var x = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
console.log(x.map(function(obj){return Object.keys(obj)[0]}));
這裏有一個解決方案使用lodash的flatMap:
let result = _.flatMap(data, _.keys);
這個土生土長的ES5解決方案,它保留了重複鍵是:
var objects = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
var keys = [];
for (var obj in objets) {
keys.push(Object.keys(obj)[0]);
}
真正偉大的答案,最後一刻落敗的職位,但許多感謝 - 希望你會得到很多讚揚+1 – danday74