5

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?

3
  • There is also Object.enteries where you get [key, value]
    – chriss
    Mar 3, 2019 at 23:50
  • Did you end up doing your own profiling? Feb 2, 2022 at 13:24
  • Wow this is old :P Back then jsperf was up, and another comment mentioned that .keys tended to be faster. But I remember noticing that it also depended on the browser (but that seems strange? I don't know TBH), so I'd just honestly pick what feels more natural. In my example I don't need the keys at all (just the number of cats in each) so I'd pick .values Feb 2, 2022 at 16:33

7 Answers 7

10

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

4
  • Thank you for your great answer! Do you know if there's a difference in terms of performance? Mar 4, 2019 at 6:53
  • 2
    Object.keys is slightly faster when dealing with huge arrays jsperf.com/object-keys-vs-for-in-with-closure/111 but code clarity and readability is far more important 99% of the time.
    – Snow
    Mar 4, 2019 at 7:00
  • Thank you! I'm dealing with large objects so it could make a difference (believe it or not, the cats breeds object wasn't real). Mar 4, 2019 at 7:34
  • 1
    Note that I ran the tests on Firefox andObject.values is 2x faster than Object.keys. It seems that the trend on Chrome is the opposite. Mar 4, 2019 at 7:35
4

Array.from(arrayLike [, mapFn [, thisArg]]) is also another method to create an array from an array-like or iterable object and is really simple. Second argument is a map function to call on every element of the array

 const cats = {
    abyssinian: {
      number: 23
    },
    persian: {
      number: 12
    },
    siamese: {
      number: 7
    }
};
const catsArray = Array.from(Object.values(cats), breed => breed.number)
console.log(catsArray);

1
  • -1 If they had a separate operation to convert something to an array, followed by map(), it would make sense to combine them using Array.from(). But in this case, they already have an actual array. So what is the point of Array.from()? Feb 2, 2022 at 13:19
2

Since you're not actually using the keys, you can use reduce with Object.values and destructuring to make it simpler and more concise:

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

const totalCats = Object.values(cats).reduce((acc, { number }) => acc + number, 0);

console.log(totalCats);

2
  • What advantage does this have: ((acc, { number }) vs. ((acc, number)?
    – zer00ne
    Mar 4, 2019 at 1:15
  • Because it's more concise than (acc, curr) => acc + curr.number Mar 4, 2019 at 2:16
0

If performance is a factor, you may want to stick with Object.keys

Here is another person's comparison on the performance of the different ways to iterate over an object.

“5 Techniques to Iterate Over JavaScript Object Entries and their Performance”

1
  • Thanks for the article! I wonder if the results would be different on Firefox, for example (cf. this other comment) Mar 4, 2019 at 8:22
0

const object1 = { "11-15" : 115, "16-20" : 68, "21-25" : 4, "26-30" : 0 };

const result = Object.keys(object1).map((key) => {return {name:key, population:object1[key]}});

//[{ name: "11-15", population: 115 }, { name: "16-20", population: 68 }, { name: "21-25", population: 4 }, { name: "26-30", population: 0 }]

console.log(result);

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Mar 4, 2022 at 6:57
-1
var total = Object
  .entries(cats)
  .reduce((acc, [name, {number}])=> acc + number , 0);
console.log(total); // 42
-1
const iterableValues = function* (obj) { for (let i of Object.values(obj)) yield i;}
let result = 0;
for (let {number} of iterableValues(cats)) result += number;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.