gpt4 book ai didi

javascript - 方法赋值JS

转载 作者:行者123 更新时间:2023-11-29 18:43:09 26 4
gpt4 key购买 nike

有一个函数可以将键“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))

关于javascript - 方法赋值JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667261/

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