Javascript: rewrite object keys and values in one line

Elvis Ciotti
2 min readJul 15, 2024

--

tl;dr;

Use Object.entries, adds a map or filter on the values, then recreate the object with Object.fromEntries

# append prefix to keys and values
Object.fromEntries(
Object.entries({a: 1, b: 2})
.map(([k, v]) => [k + '_k', v + '_v'])
); // { a_k: '1_v', b_k: '2_v' }

The problem

In js you can easily use array map and filter to change items in an array. If you don’t know them, have a look at how they work first.

When you want to do similar operations to an object (e.g. rewriting keys or values), there is no corresponding function.

You could of course iterate the object, but you can also do that in a single line combining

  • Object.entries that transforms an object into the array representation, that is an array of 2-elements array (each one holding key and value as element). Look carefully as the example as you need to understand this before reading the rest
Object.entries({a: 1, b: 2}); // [     [ 'a', 1 ],   [ 'b', 2 ]    ]
  • Object.fromEntries that takes an array of array (same format as the ouput above) and creates the object from it. So basically the reverse function
Object.fromEntries( [ [ 'a', 1 ], [ 'b', 2 ] ]); // {a: 1, b: 2}

So, since Object.entries creates an array representation of an object, and Object.fromEntries creates the object from it, this command basically returns the input object.

Object.fromEntries(Object.entries({a: 1, b: 2})); // {a: 1, b: 2}

The good thing is that we can operate on the entries as an array before re-transforming into an object.

If I want to modify key and values I can simply call a “map” on the “entries” output, where the function accepts key and value that I have to return transformed

// add a "_k" prefix to keys and "_v" to values
Object.fromEntries(
Object.entries({a: 1, b: 2})
.map(([k, v]) => [k + '_k', v + '_v'])
); // { a_k: '1_v', b_k: '2_v' }

And if I want to filter then, I can do the following

// filter out odd values
Object.fromEntries(
Object.entries({a: 1, b: 2, c: 3, d: 4})
.filter(([k, v]) => v % 2 === 0)
); // { b: 2, d: 4 }

Clap if useful

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet