Today I Learned

hashrocket A Hashrocket project

`Object.entries` helps you iterate over objects

You may find yourself with an object with lots of entries that you need to transform into an array of extracted information. For examples sake lets say:

  const things = {
    a: 1,
    b: 2
  }

And we need to turn that into and array [2, 3].

We can use Object.entries to turn the object into an array of key/value tuples.

const arr = Object.entries(things)
// arr === [["a", 1], ["b", 2]]

Then we can iterate over that array with map:

const mappedArr = arr.map((tuple) => {
  const [key, value] = tuple;
  return value + 1;
});
// mappedArr === [2, 3]

Object.entries is an ES7 proposal implemented in Chrome/Firefox/Edge and polyfilled with CoreJS, the polyfill library used by Babel.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.