brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Object.fromEntries() turns key-value pairs back into an object

Web-Development
~/tips/tip-javascript-object-fromentries

const safe = Object.fromEntries(

Builds a plain object from an array or Map of key-value pairs, handy after filtering entries.

JavaScript has plenty of array helpers, but objects get fewer. I like Object.fromEntries() because it closes the loop: Object.entries() turns an object into pairs, and this turns pairs back into an object.

The combination gives you map and filter for objects. Say you have a user record and want to send it to a log without the password:

const user = { name: "Ada", age: 36, password: "secret", role: "admin" };

const safe = Object.fromEntries(
  Object.entries(user).filter(([key]) => key !== "password")
);
// { name: "Ada", age: 36, role: "admin" }

The same trick works for changing values. This one trims every string in a form object:

const cleaned = Object.fromEntries(
  Object.entries(form).map(([k, v]) => [k, typeof v === "string" ? v.trim() : v])
);

It also takes a Map directly, which is the quickest way to get a plain object you can pass to JSON.stringify(). A Map does not serialize on its own, it comes out as {}:

const map = new Map([["foo", "bar"], ["baz", 42]]);
Object.fromEntries(map); // { foo: "bar", baz: 42 }

One caveat: if a key shows up twice, the later pair wins and the earlier one is silently dropped. Also, keys always become strings (or symbols), so a Map with number or object keys loses that information. The result is a plain object, so it does not keep a class or prototype from the original either.

It has been in all major browsers since January 2020, so there is no reason to reach for a library like lodash just to omit one field.

Further reading: MDN: Object.fromEntries()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link