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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With