一、效果
![](https://i-blog.csdnimg.cn/blog_migrate/bffdbad4e075e196eacadc4495f299fd.png)
二、代码
<script>
const options = [
{ key: 1, msg: "小黑" },
{ key: 2, msg: "小绿" },
{ key: 3, msg: "小白" },
{ key: 4, msg: "小蓝" },
{ key: 5, msg: "小黄" },
]
</script>
① map方式
<script>
//const newOptions = options.map((item) => ({ value: item['key'], label: item['msg'],}));
const newOptions = options.map((item)=>{
return {
value: item['key'],
label: item['msg'],
}
})
console.log("newOptions", newOptions);
</script>
② replace方式
<script>
let newOptions1 =
JSON.parse(JSON.stringify(options).replace(/msg/g,"label").replace(/key/g, "value"));
console.log("newOptions1", newOptions1);
</script>
③ reduce方法
<script>
const newOptions2 = options.reduce((acc, cur) => {
const {key,msg, ...rest} = cur;
acc.push({value: key,label:msg, ...rest});
return acc;
}, []);
console.log('newOptions2',newOptions2);
</script>
④ for循环
<script>
for(let i = 0; i < options.length; i++){
options[i].value = options[i].key;
options[i].label = options[i].msg;
delete options[i].key;
delete options[i].msg;
}
console.log('options',options);
</script>