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