Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

javascript - JavaScript:如何重命名对象中的所有键(在第一级处理所有键)? [重复](JavaScript: how to rename all keys in an object (process all keys on the first level)? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

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):

(为了减少歧义,我希望可以显示Python中的字典理解是实现此目的的一种优雅方法(我正在寻找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?

(在现代JavaScript中,这是一种类似的优雅且特别易读的方式,理想的方式是在NodeJS 12中使用吗?)

  ask by Jan-Philip Gehrcke translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Convert the object to entries via Object.entries() .

(通过Object.entries()将对象转换为条目。)

Iterate the entries with Array.map() and update the key.

(使用Array.map()迭代条目并更新密钥。)

Convert the entries to object using Object.fromEntries() :

(使用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) 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...