10

I have an object with the following format

var obj = [{
  "a": 1
}, {
  "b": 2
}, {
  "c": 3
}];

Would want to fetch only keys out of each object inside this array of objects into a new array

Something like this: ["a","b","c"]

Have tried the following but it is not working :

var obj = [{
  "a": 1
}, {
  "b": 2
}, {
  "c": 3
}];
let result = obj.map (({ val }) => val)
console.log(result);

4 Answers 4

21

Merge to a single object by spreading into Object.assign(), and then get the keys:

var obj = [{"a":1},{"b":2},{"c":3}];

const result = Object.keys(Object.assign({}, ...obj));
console.log(result);

Or use Array.flatMap() with Object.keys():

var obj = [{"a":1},{"b":2},{"c":3}];

const result = obj.flatMap(Object.keys);
console.log(result);

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

3 Comments

Liking the second the best
There may be a slight difference between the 2 options if the objects have similar keys: the Object.assign method will return unique keys while the flatMap method will return all the keys per object regardless of any duplicates.
Yep. You'll need to use a Set to get unique keys if you prefer the 2nd option.
2

I'd .map and extract the first item in the Object.keys of the object being iterated over:

var obj = [{
  "a": 1
}, {
  "b": 2
}, {
  "c": 3
}];

const result = obj.map(inner => Object.keys(inner)[0]);
console.log(result);

1 Comment

Doesn't work if an object in the array has multiple keys
2

You can make use of Object.assign and spread(...) operator to solve this issue

var mainObj = [{"a":1},{"b":2},{"c":3},{"23":1},{"32b":2},{"232c":3}];

const allKeys = Object.keys(Object.assign({}, ...mainObj));
console.log(allKeys);

Comments

1

You can simply use .map() to open the array and then use Object.keys to return the key from the object. Please refer the example I have made.I hope it helps

https://www.w3schools.com/code/tryit.asp?filename=G66AEBM9ZJCD

let object1 = [{a:1,b:2,c:3}]
        let final = object1.map(function(object){ 
            return Object.keys(object)
        });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.