简体   繁体   中英

JavaScript to get array of keys from array of objects

I have this array, each object in the array has one key only:

[{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]

I want to extract all the keys into an array such that the result I want is:

["hello", "there", "everybody"]

What's a succinct way of doing this in Lodash or vanilla JavaScript (preferably ES6)?

You can use Array#map together with Object.keys .

 let arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]; let keys = [].concat(...arr.map(Object.keys)); console.log(keys); 

Combine to a single object using Object#assign , and retrieve the keys from the object using Object#keys :

 const arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]; const keys = Object.keys(Object.assign({}, ...arr)); console.log(keys); 

And the ES5 version using lodash's _.assign() with _.spread() to combine to a single object, and _.keys() to get the 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> 

You can use array map combining with object keys :

const array = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];

const result = array.map((el) => Object.keys(el)[0]);

 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);

A native ES5 solution for this that preserves duplicate keys would be:

var objects = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
var keys = [];
for (var obj in objets) {
    keys.push(Object.keys(obj)[0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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