如何动态更改数组中对象属性的键名

时间:2017-01-13 14:53:49

标签: javascript arrays javascript-objects

我有一个对象数组,如下所示:

arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}]

每个对象将始终包含“时间段”属性,并且可以包含星期一到星期日的星期属性的任意组合。一周中的每一天只能在一个对象中表示一次。

我想改变每个对象:具体来说,星期几属性的键名(“时段”属性将保持不变“),以获得类似的数组这样:

newArr = [{"timeslot":"6am7am","Monday":10,"Tuesday":11,"Wednesday":7}]

我的不可读的解决方案有效:

// Iterate the array of objects
results.forEach(function(o) {
    // Iterate the object's properties
    Object.keys(o).forEach(function(k) {
        if(k.includes("AVG")) {
            var len = k.length;
            var pos = len - 1;
            var newKey = k.slice(4, pos); // Extract the day of the week from the key name
            o[newKey] = o[k]; // Create the new property with the same value and the new key-name
            delete o[k]; // Delete the original property
        }
    });
});

如何改进此解决方案?

1 个答案:

答案 0 :(得分:1)

不是通过在每个对象中添加和删除键来改变原始数组,而是将数组Array#map转换为新数组,然后使用Array#reduce重新创建对象:



var arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}];

var result = arr.map(function(obj) {
  return Object.keys(obj).reduce(function(r, key) {    
    var k = key.includes('AVG') ? key.slice(4, -1) : key;
    
    r[k] = obj[key];
    
    return r;
  }, {});
});

console.log(result);