javascript - 方法赋值JS
问题描述
有一个函数可以将密钥“certificate”更改为“certificate_car”。有没有办法通过直接使用assign方法更改数组来改进功能?可能吗?
const arr = [{
"name": "BMW",
"price": "55 000",
"country": "Germany",
"certificate": "yes"
},
{
"name": "Mercedes-benz",
"price": "63 000",
"country": "Germany",
"certificate": "yes"
},
{
"name": "Mitsubishi",
"price": "93 000",
"constructor": "Bar John",
"door": "3",
"country": "Japan",
},
{
"name": "TOYOTA",
"price": "48 000",
"max_people": "7",
"country": "Japan",
"certificate": "yes"
},
{
"name": "Volkswagen",
"price": "36 000",
"constructor": "Pier Sun",
"country": "Germany",
"certificate": "no"
},
];
function certificateCar(arr) {
return arr.map(function(item) {
let itemCar = {};
let newItem = Object.assign({}, item);
Object.keys(newItem).forEach(item => {
itemCar[item.replace("certificate", "certificate_car")] = newItem[item]
});
return itemCar;
})
}
console.log(certificateCar(arr))
解决方案
您可以使用解构并更改所需的键名并保持其余部分不变
const arr = [{"name":"BMW","price":"55 000","country":"Germany","certificate":"yes"},{"name":"Mercedes-benz","price":"63 000","country":"Germany","certificate":"yes"},{"name":"Mitsubishi","price":"93 000","constructor":"Bar John","door":"3","country":"Japan",},{"name":"TOYOTA","price":"48 000", "max_people":"7","country":"Japan","certificate":"yes"},{"name":"Volkswagen","price":"36 000", "constructor":"Pier Sun","country":"Germany","certificate":"no"}, ];
const certificateCar = (arr) =>
arr.map(({certificate,...rest}) =>({...rest,certificate_car:certificate}))
console.log(certificateCar(arr))
推荐阅读
- kubernetes - 启用 istio 的微服务在 tcp keepalive 方面的行为
- android - 在 KOTLIN 中使用改造向 API 添加动态参数
- asp.net-core - 为 ASP.NET Core 中的每个对象创建唯一的路由
- sql - 错误:运算符不存在:bigint = bigint[]
- php - 如何使用 PHP 将 MySQLi 转换为 PDO
- api - Api 给出错误的数据
- python - 在 tkinter 中调整窗口大小时动态调整小部件的大小
- sql - 为每个唯一 ID 随机化日期字段中的时间
- c++ - C++ 基准代码崩溃 - 长数字
- powershell - powershell 不能对反向引用匹配使用方法