2

I am wondering what is a better approach to extract all the keys and values of objects in an array as separate arrays. My approach requires me to flatten the array after extracting keys and values of the object by mapping over the array.

Input

const input = [{"a": 1, "b": 2}, {"c": 3}, {"d": 4}, {}, {"e": null, "f": 6, "g": 7}];

Output

const keys = ["a", "b", "c", "d", "e", "f", "g"];

const values = [1, 2, 3, 4, null, 6, 7];

My Solution

const input = [{
  "a": 1,
  "b": 2
}, {
  "c": 3
}, {
  "d": 4
}, {}, {
  "e": null,
  "f": 6,
  "g": 7
}];
const keys = input.map(obj => [].concat(Object.keys(obj))).flat();
console.log(keys);
const values = input.map(obj => [].concat(Object.values(obj))).flat();
console.log(values);

2
  • 2
    This would be a question for CodeReview Commented Nov 28, 2019 at 9:08
  • Aah, thanks for introducing me to this wonderful platform. Commented Nov 28, 2019 at 9:09

3 Answers 3

4

You can use the flatMap which is what you have implemented

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

const input = [{
  "a": 1,
  "b": 2
}, {
  "c": 3
}, {
  "d": 4
}, {}, {
  "e": null,
  "f": 6,
  "g": 7
}];

const keys = input.flatMap(Object.keys);
const values = input.flatMap(Object.values);

console.log(keys,values)

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

1 Comment

There is no need to create a new callback function. You can just do flatMap(Object.keys)... etc.
1

Try one reduce function so you don't do two loops, and get it all done in one loop?

const input = [{
  "a": 1,
  "b": 2
}, {
  "c": 3
}, {
  "d": 4
}, {}, {
  "e": null,
  "f": 6,
  "g": 7
}];

const { keys, values } = input.reduce((accum, obj) => ({
  keys: [...accum.keys, ...Object.keys(obj)],
  values: [...accum.values, ...Object.values(obj)],
}), { keys: [], values: [] });

console.log(keys, values)

Comments

0

You can get key and then flat an array:

const input = [
  { "a": 1, "b": 2 },
  { "c": 3 }, { "d": 4 },
  {},
  { "e": null, "f": 6, "g": 7 }
];

const keys = input.map(a=> Object.keys(a)).flat();
const values = input.map(a=> Object.values(a)).flat();

console.log(keys)
console.log(values)

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.