0

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

0

6 Answers 6

5

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>

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

3

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

Comments

1

var x = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];

console.log(x.map(function(obj){return Object.keys(obj)[0]}));

Comments

1

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

Comments

1

Here's a solution using lodash's flatMap:

let result = _.flatMap(data, _.keys);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.