101.JavaScript动态改变一个对象的key值

var array = [
{
id: 1,
name: “小明”
},
{
id: 2,
name: “小红”
}
];

方法1:map函数

写法1:箭头表达式

var result = array.map(o => { return { value: o.id, label: o.name } });
console.log(result);

写法2:匿名函数

var arr = [
{
id: 1,
name: “小明”
},
{
id: 2,
name: “小红”
}
];
var newArr = arr.map(function (item) {
return {
value: item[‘id’],
lable: item[‘name’]
}
})
console.log(newArr)

方法2:循环遍历【正则表达式】

var array = [
{
id: 1,
name: “小明”
},
{
id: 2,
name: “小红”
}
];
function convertKey(arr, keyMap) {
let tempString = JSON.stringify(arr);
for (var key in keyMap) {
var reg = /"${key}":/g;
tempString = tempString.replace(eval(reg), ‘“‘ + keyMap[key] + ‘“:’);
}
return JSON.parse(tempString);
}
convertKey(array, { ‘id’: ‘value’, ‘name’: ‘label’ });

方法3:循环遍历【双重for循环】

/**/
//旧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);
101.JavaScript动态改变一个对象的key值 - 图1

方法4:递归遍历【树形结构】

const transformModel = (object = {}, keymap = {}) => {
if (typeof object !== ‘object’ || object === null) return object
if (Array.isArray(object)) {
return object.map(value => transformModel(value, keymap))
}
return Object.keys(object).reduce((result, curkey) => {
const rule = keymap[curkey]
const value = object[curkey]
const [newkey, submap] = Array.isArray(rule) ? rule : [rule]
return Object.assign({}, result, {
[newkey || curkey]: transformModel(value, submap)
})
}, {})
}
const testKeyMap = {
name: ‘title’,
detail: [, {
content: ‘body’,
viewCount: ‘vc’
}],
imgs: [‘images’, {
text: ‘name’
}]
}
const testOriginObj = {
name: ‘名称’,
detail: {
content: ‘内容’,
viewCount: ‘浏览量’,
other: ‘未定义项’
},
imgs: [
{ text: ‘图片1’ },
‘图片2’
],
other: ‘未定义项’
}
console.log(testOriginObj)
console.log(transformModel(testOriginObj, testKeyMap))

方法5:Object.keys【树形结构】

sourceObj = {
“name”: ‘zhangsan’,
“age”: ‘16’
}
targetObj = {
“label”: ‘zhangsan’,
“value”: ‘16’
}
let keymap = {
name: “label”,
age: ‘value’
}
Object.keys(sourceObj).map(keys => {
let newKey = keymap[keys]
if (newKey) {
sourceObj[newKey] = sourceObj[keys]
delete sourceObj[keys]
}
})

  • 实际使用:

IndustryData(arr) {
arr.forEach(v => {
let keymap = {
categoryId: “id”,
children: ‘children’,
name: “label”,
order: ‘order’,
parentId: “parentId”,
}
Object.keys(v).map(keys => {
let newKey = keymap[keys]
if (newKey) {
v[newKey] = v[keys]
}
})
if (v.children && v.children.length > 0) {
this.IndustryData(v.children)
} else {
delete v[‘children’]
}
})
return arr
}