[SOLVED] Creating an array from object properties with Object.keys() vs Object.values()

Issue

Here’s an object of cat breeds, and the number of cats in each:

const cats = {
  abyssinian: {
    number: 23
  },
  persian: {
    number: 12
  },
  siamese: {
    number: 7
  }
};

Suppose I wanted to calculate the total sum of cats. I’ll use reduce to calculate the sum of array values.

But to create an array from the object above, I have two options:

  1. Object.keys()
  2. Object.values()
// object
const cats = { abyssinian: { number: 23 }, persian: { number: 12 }, siamese: { number: 7 } };

// sum array values with reduce
const total = numbers => numbers.reduce((acc, cur) => acc + cur);

// 1.
// create array with Object.keys()
const numbersByKeys = Object.keys(cats).map(breed => cats[breed].number);
console.log(`Sum with Object.keys(): ${total(numbersByKeys)}`);

// 2.
// create array with Object.values()
const numbersByValues = Object.values(cats).map(breed => breed.number);
console.log(`Sum with Object.values(): ${total(numbersByValues)}`);

When would I choose one over the other? What are the best practices here?

Solution

Use .keys() if you need to do something with the keys other than to retrieve the values. Otherwise, you’re only getting the keys in order to access the values, which is redundant if you can get the values directly using a different method – so, in that case, might as well use Object.values() from the beginning.

An example of where Object.keys could be useful:

const obj = {
  prop1: 'val1',
  prop2: 'val2'
};

const result = Object.keys(obj).map((key) => [key, obj[key]]);
console.log(result);

You may also use Object.entries to get both the key and value at once:

const obj = {
  prop1: 'val1',
  prop2: 'val2'
};

const result = Object.entries(obj).map(([key, val]) => key + '---' + val);
console.log(result);

Answered By – Snow

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *