Object.fromEntries() Method
I'm writing to you from lovely Boulder, Colorado today. I'm in town visiting my brother, sister-in-law, and niece for a couple of days. The beer here is delicious and the weather is cool with intermittent showers. I'm only here for another day before I head to Denver to attend DinosaurJS -- something I'm both excited and nervous about. Excited because I'll be in a room full of way better developers than myself, and nervous for the exact same reason.
When I first started the Array Methods series (links to which are at the bottom of this post, and all posts in the series), my plan was to simply go through the mentioned episode of the Syntax podcast (link also below because I'm lazy). However, I just ran across this tweet by Mathias Bynens which says that Object.fromEntries()
has shipped to Chrome, Safari, Firefox, and Node.js. Having just finished posts on Object.keys()
, Object.values()
, and Object.entries()
, the premiere of this brand new object method couldn't be better timed.
Where Object.entries()
will take a data object and produce an array of arrays which consist of the [key, value]
pairs, Object.fromEntries()
will work in the opposite direction, taking an array of arrays (or a map) of [key, value]
pairs and produce an object. Let me once again borrow from some of the same examples I've given in those other posts.
const objEntries = [["name", "Joey"], ["age", 31], ["occupation", "Web Developer"], ["location", "Austin, Texas"], ["hungry": true]];
const person = Object.fromEntries(objEntries);console.log(person);// expected output:// const person = {// name: "Joey",// age: 31,// occupation: "Web Developer",// location: "Austin, Texas",// hungry: true,// }
Once again, let me do my best to recreate this behavior with the methods previously available, this time with a .forEach()
:
const person = {};const entries = [ ["name", "Joey"], ["age", 31], ["occupation", "Web Developer"], ["location", "Austin, Texas"], ["hungry", true],];
entries.forEach((entry) => { person[entry[0]] = entry[1];});
console.log(person);// expected output:// const person = {// name: "Joey",// age: 31,// occupation: "Web Developer",// location: "Austin, Texas",// hungry: true,// };
And that's that! So excited to be writing about something new.
From MDN: The Object.fromEntries()
method transforms a list of key-value pairs into an object.
See more examples and documentation here.