3

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

1
  • What doe you expect the result to be? Commented Jun 23, 2019 at 18:35

3 Answers 3

6

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)

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

Comments

2

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)

2 Comments

Could be just flatMap(Object.keys)
@georg yeah. I just copied OP's code. And, Bergi has already suggested that.
1

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

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.