Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys out of array of objects : Javascript

I have this scenario where I need to fetch only the keys in an array of objects. Object structure is shown below. I have also tried an approach but it does not seem like working. Can someone help me out with this.

var arr = [
        { firstName: "aaaaa", status: 0, visits: 155 },
        { firstName: "aabFaa", status: 0, visits: 155 },
        { firstName: "adaAAaaa", status: 10, visits: 1785 },
        { firstName: "aAaaaa", status: 50, visits: 175 },
        { firstName: "aaaaa", status: 670, visits: 155 },
      ]

console.log([...new Set(arr.map(item => Object.keys(item)))]); //  This does not work

I want the output to be just ['firstName','status','visits']

like image 906
joy08 Avatar asked Jun 11 '26 07:06

joy08


1 Answers

Object.keys does itself return an array, so your map creates an array of arrays. Use flatMap instead:

console.log(Array.from(new Set(arr.flatMap(Object.keys))))

Alternatively, since all objects in your array have the same keys, you could just take those of the first object:

console.log(Object.keys(arr[0]))

(this also makes it obvious that the code only works on non-empty arrays)

like image 176
Bergi Avatar answered Jun 13 '26 19:06

Bergi



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!