gpt4 book ai didi

javascript - 在 ES6 中重命名对象属性的最佳方式

转载 作者:行者123 更新时间:2023-11-30 14:44:50 25 4
gpt4 key购买 nike

我还在学习 js,我需要一个建议。我从后端获取 json 对象,但键有下划线。将键重命名为(例如 folder_name 为文件夹名称)的最佳做法是什么?属性列表是已知的并已完成,因此我可以将新名称保留在常量中。在前端我已经这样使用它了:

const showPropertiesList = properties => Object.keys(properties).map(property => (
<PropertyKey key={property}}>
`${property}: ${properties[property]}`
</PropertyKey>
));

最好在此映射中使用重命名函数或之前创建单独的函数来获取所有重命名的键和值?

json文件:

properties {
folder_name: 'test',
user_email: 'test@example.com',
user_agreed: 1,
site: 'example.com',
}

最佳答案

您可以创建某种映射 对象,然后使用以下Object.keys 的组合和 reduce功能:

const properties = {
folder_name: "test",
user_email: "test@example.com",
user_agreed: 1,
site: "example.com"
};

const mapping = {
folder_name: "Folder name",
user_email: "User email",
user_agreed: "User agreed",
site: "Site"
};

const mapped = Object.keys(properties).reduce((acc, key) => {
acc[mapping[key]] = properties[key];
return acc;
}, {});

console.log(mapped);

关于javascript - 在 ES6 中重命名对象属性的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49102256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com