Home > Mobile >  Get array of object property names from array of objects
Get array of object property names from array of objects

Time:10-20

I'm looking for something similar to this:

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

However in my example I have:

const objectArray1 = [
  { a: 112, b: 322, c: 233 },
  { a: 611, b: 232, c: 331 },
  { a: 132, b: 232, c: 342 }
];

What's the most efficient way of getting the ["a", "b", "c"] from this?

Also, that'll probably never happen but if one of objectArray1 objects has d: 345 in it or a missing key/value pair, that needs to be handled.

Any ideas?

CodePudding user response:

Map all entries of objectArray1 to the object's keys using Object.keys and flatMap, to get a flat array of all keys in all objects.
Then pass it through a Set to extract the unique values. The Set can be converted back to an array using the ... spread operator:

const objectArray1 = [
  { a: 112, b: 322, c: 233 },
  { a: 611, b: 232, c: 331 },
  { a: 132, b: 232, c: 342 },
  { a: 132, b: 232, c: 342, d: 532 }
];

const keys = [
  ...new Set(objectArray1.flatMap(Object.keys))
];

console.log(keys)

CodePudding user response:

You should use Object.keys in this case

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

const result = Object.keys(object1)

console.log(result)

If you have an array, you also can add Set to filter unique keys

const objectArray1 = [
  { a: 112, b: 322, c: 233 },
  { a: 611, b: 232, c: 331 },
  { a: 132, b: 232, c: 342 }
];

const result = Array.from(new Set(objectArray1.flatMap((value) => Object.keys(value))))

console.log(result)

CodePudding user response:

I would personally use flatMap() with Object.keys(), and then make a new unique array from it using new Set() with spread operator ... .

const objectArray1 = [
  { a: 112, c: 233 },
  { b: 232, c: 331 },
  { a: 132, b: 232, c: 342, d: 5 }
]


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

console.log(uniqueKeys(objectArray1))
//expected ["a", "b", "c", "d"]

  • Related