js如何修改对象的key值?

原数据:

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

我要改为的数据:

var array = [
    {
        value:1,
        label:"小明"
    },
    {
        value:2,
        label:"小红"
    }
];

对应的值不变,只是改key的名称,用js如何实现呢?

回复
阅读 51.8k
7 个回答
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);
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'});

keyMap是你要替换的键值对映射

var array = [
    {
        id:1,
        name:"小明"
    },
    {
        id:2,
        name:"小红"
    }
];
const result = array.map(item => ({value:item.id, name: item.name}))
console.log(result)
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))
新手上路,请多包涵
var arr = [
                {
        id:1,
        name:"小明"
    },
    {
        id:2,
        name:"小红"
    }
            ];
            var newArr = arr.map(function(item) {
                return {
                    value: item['id'],
                    lable: item['name']
                }
            })
            console.log(newArr) 
新手上路,请多包涵

简单改造了一下,支持传入 对象数组对象

const replaceKeys = (obj, keysMap) => {
  if (Array.isArray(obj)) {
    return obj.map((item) => replaceKeys(item, keysMap));
  } else {
    return Object.keys(obj).reduce((acc, key) => {
      const newKey = keysMap[key] || key;
      acc[newKey] = obj[key];
      return acc;
    }, {});
  }
};

const userList = [
  { name: 'sam', age: 30, gender: 'male' },
  { name: 'yy', age: 18, gender: 'female' },
];
replaceKeys(userList, { gender: 'sex' });
// [{ name: 'sam', age: 30, sex: 'male' }, { name: 'yy', age: 18, sex: 'female' }]

const user = { name: 'yy', age: 18, gender: 'female' };
replaceKeys(user, { gender: 'sex' });
// { name: 'yy', age: 18, sex: 'female' }
推荐问题
宣传栏