js如何修改对象的key值?

Codermin
  • 527

原数据:

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

我要改为的数据:

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

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

回复
阅读 33.6k
6 个回答
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是你要替换的键值对映射

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

宣传栏