1

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?

0

3 Answers 3

5

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)

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

Comments

3

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)

Comments

0

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

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.