不删除旧的key和value:

var data = [
	{name: "路口1", count: "30"},
    {name: "路口2", count: "20"},
    {name: "路口3", count: "10"}
]
data = data.map(item => ({
	 ...item,
    value: item.count
}));

得到:
{name: ‘路口1’, count: ‘30’, value: ‘30’},
{name: ‘路口2’, count: ‘20’, value: ‘20’},
{name: ‘路口3’, count: ‘10’, value: ‘10’}

删掉旧的key和value:

方法一:使用map循环,在map循环内创建一个新对象,将item要改变的key赋给新创建的对象里面新key值,然后push给一个新创建的数组dataNew即可;

let dataNew = [];    //新数组
data.map(item => {
    let obj = {
        name: item.name,
        value: item.count,
    }
     dataNew.push(obj);
});

方法二:使用forEach循环 + for循环,通过Object.keys()来改变属性key;

function convertKey (arr, key) {
    let dataNew = []; //新数组
    data.forEach((item, index) => {
        let obj = {}; //新数组里的新对象
        for (var i = 0; i < key.length; i++) {
            obj[key[i]] = item[Object.keys(item)[i]]; //key值替换  
        }
        dataNew.push(obj);
    })
    console.log(dataNew,'dataNew');
    return dataNew;
}

let dataNew = this.convertKey(data, ['name','value']);
Logo

前往低代码交流专区

更多推荐