爱生活,爱编程,学习使我快乐
原数据:
var array = [
{
id:1,
name:"小明"
},
{
id:2,
name:"小红"
}
];
要改为:
var array = [
{
value:1,
label:"小明"
},
{
value:2,
label:"小红"
}
];
对应的值不变,只是改key的名称,用js如何实现呢?
方法一:
var array = [
{
id:1,
name:"小明"
},
{
id:2,
name:"小红"
}
];
//旧key到新key的映射
var keyMap = {
"id" : "value",
"name" : "label"
};
for(var i = 0;i < array.length;i++){
var obj = array[i];
for(var key in obj){
var newKey = keyMap[key];
if(newKey){
obj[newKey] = obj[key];
delete obj[key];
}
}
}
console.log(array);
方法二:
var result = array.map(o=>{return{value:o.id, label:o.name}});
console.log(result);