简体   繁体   English

在 JavaScript 中更改对象的键

[英]Change Keys of an Object in JavaScript

I want to change such an object:我想改变这样一个对象:

inputObj = {
    "1": 10,
    "2": 20,
    "3": 30,
    "4": 40,
    "5": 50,
    "6": 60
}`

to this:对此:

outputObj = {
    "one": 10,
    "two": 20,
    "three": 30,
    "four": 40,
    "five": 50,
    "six": 60
}

can anybody help?有人可以帮忙吗? The keys are taken from the database as numbers.密钥以数字形式从数据库中获取。 but I need to change them to descriptions但我需要将它们更改为描述

i think the below snippet will solve the issue.我认为下面的代码段将解决这个问题。

you need to take the key of input and map over it and change with replacementConfig and update it.您需要获取输入的键并对其进行映射,并使用replacementConfig 进行更改并更新它。 See the below snippet看下面的片段

 const replacementsConfig = {"1": "one", "2": "two", "3": "three"}; const data = {'1': 10, '2': 30 , "3": 69 }; let replacedItems = Object.keys(data).map((key) => { const newKey = replacementsConfig[key] || key; return { [newKey] : data[key] }; }); let output = Object.assign(...replacedItems) console.log(output)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM