joy08
joy08

Reputation: 9662

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']

Upvotes: 3

Views: 74

Answers (3)

adiga
adiga

Reputation: 35259

You are trying to create a Set from a 2D array of keys. Use flatMap to get a flattened array of keys of all the objects in the array

[...new Set(arr.flatMap(item => Object.keys(item)))]

Here's a snippet:

const 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 },
    ];
    
const uniqueKeys = [...new Set(arr.flatMap(Object.keys))]

console.log(uniqueKeys)

Upvotes: 2

connexo
connexo

Reputation: 56823

Object.keys(arr[0]) is probably the shortest solution, assuming each object in arr has the same keys:

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
  },
]

let keys = Object.keys(arr[0]);

console.log(keys);

Upvotes: 1

Bergi
Bergi

Reputation: 665527

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)

Upvotes: 6

Related Questions