0

Using Object.fromEntries to make a new Object

 7 months ago
source link: https://thewebivore.com/using-object-fromentries-to-make-a-new-object/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Using Object.fromEntries to make a new Object

Creating a new object from an existing one, or from an array, can have multiple solutions in JavaScript. I ran into a scenario where I had an object where the values are an array. I wanted to take this and create a new object (so I could store state related to the keys), so I wanted to dump the values and replace them for something else.

Start:

const obj = { "a" : [1,2,3], "b": [1,2,3] }

Destination:

const newObj = { "a" : "val", "b": "val" }

The values could be whatever, the point is to take the keys and then a different set of values.

I can do this with brute force by enumerating over the keys in the object and assigning them to a new one:

let newObj = {}
for (key in obj) {
    newObj[key] = "val"
}

There’s a newer (ES2019) utility, Object.fromEntries, which takes an iterable (arrays, Maps, but not an Object that you haven’t implemented an iterator on…) that can be used here:

Object.fromEntries(Object.keys(obj).map(x => [x, "foo"]))

To break it down:

// create an object from the provided entries. cool cool.
Object.fromEntries(Object.keys(obj).map(x => [x, "val"]))
// give me the keys of the obj Object; ["a", "b"]
Object.fromEntries(Object.keys(obj).map(x => [x, "val"]))
// take those keys and make tuples; [ ["a", "val" ], ["b", "val" ] ]
Object.fromEntries(Object.keys(obj).map(x => [x, "val"]))

To get to our result of

{ a: "val", b: "val" }

Writing it out, I’m hoping to understand this more so I can understand it quickly when I see it. But I found it neat to stumble on a new-to-me utility.

Posted in: Blog

Tags:javascript

Leave a Reply Cancel reply

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

Comment *

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Post navigation


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK