简体   繁体   中英

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

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)

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) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM