Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: how to rename all keys in an object (process all keys on the first level)? [duplicate]

Tags:

javascript

I would like to add a prefix to the first level of keys in an object.

To leave less ambiguity, I hope that it's OK to show how a dictionary comprehension in Python is an elegant way for achieving this (and I am looking for an analogous approach in JavaScript):

>>> old = {"a": 1, "b": 2}
>>> prefix = "_"
>>> new = {prefix + key: value for key, value in old.items()}
>>> new
{'_a': 1, '_b': 2}

What's a similarly elegant and especially readable way for doing this in modern JavaScript, ideally available in NodeJS 12?

like image 830
Dr. Jan-Philip Gehrcke Avatar asked Dec 06 '25 05:12

Dr. Jan-Philip Gehrcke


1 Answers

Convert the object to entries via Object.entries(). Iterate the entries with Array.map() and update the key. Convert the entries to object using Object.fromEntries():

const old = {"a": 1, "b": 2}
const prefix = "_"

const result = Object.fromEntries(
  Object.entries(old).map(([k, v]) => [`${prefix}${k}`, v])
)

console.log(result)
like image 192
Ori Drori Avatar answered Dec 08 '25 18:12

Ori Drori