Skip to content

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"
}

However, for…in isn’t recommended by various guides/linters. Here’s some notes from MDN:

Many JavaScript style guides and linters recommend against the use of for...in, because it iterates over the entire prototype chain which is rarely what one wants, and may be a confusion with the more widely-used for...of loop. for...in is most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise). In situations where objects are used as ad hoc key-value pairs, for...in allows you check if any of those keys hold a particular value.

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.

One Reply to “Using Object.fromEntries to make a new Object”

Leave a Reply

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

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