替换对象数组中的键

时间:2013-11-25 15:52:29

标签: javascript jquery

我有一个对象数组,想要替换所有对象中的特定键。

JAVASCRIPT

var json = [{
  acceleration: 15,
  cylinders:    4,
  displacement: 98,
  horsepower:   80

}, {
  acceleration: 14,
  cylinders:    8,
  displacement: 307,
  horsepower:   130      
}];

例如马力 - >颜色。

解决方案可能是

var json = [{
  acceleration: 15,
  cylinders:    4,
  displacement: 98,
  color:   80

}, {
  acceleration: 14,
  cylinders:    8,
  displacement: 307,
  color:   130      
}];

2 个答案:

答案 0 :(得分:1)

使用示例解决方案创建了fiddle。 使用delete删除属性,只需添加具有上一个值的另一个属性:

_.each(json, function(element) {
    var val = element.horsepower;
    delete element.horsepower;
    element.color = val;
});

PS。使用underscorejs编码方便,普通的javascript将是:

var i;
for (i=0; i<json.length; i++) {
    var element = json[i];
    var val = element.horsepower;
    delete element.horsepower;
    element.color = val;
}

答案 1 :(得分:-1)

var array = [{
  acceleration: 15,
  cylinders:    4,
  displacement: 98,
  horsepower:   80

}, {
  acceleration: 14,
  cylinders:    8,
  displacement: 307,
  horsepower:   130      
}];
for (var i = 0; i < array.length; i++) {
    var horsepower = array[i].horsepower;
    array[i].horsepower = undefined;
    array[i].color = horsepower;
}