var array = [
{
id:1,
name:"小明"
},
{
id:2,
name:"小红"
}
];
转换为
var array = [
{
value:1,
label:"小明"
},
{
value:2,
label:"小红"
}
];
办法一:
插入新的 key 与值删除旧的 key 与值
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);
办法二:
利用数组的 map 办法遍历批改原数组对象
var result = array.map(o=>{return{value:o.id, label:o.name}});
console.log(result);