Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting key of each object inside array of objects into an array: Javascript

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);
like image 447
joy08 Avatar asked Apr 16 '26 08:04

joy08


1 Answers

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);
like image 152
Ori Drori Avatar answered Apr 17 '26 22:04

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!