使用javascript重命名数组中的Object Key

时间:2015-03-12 10:16:31

标签: javascript json angularjs html5

在我的角度应用程序中,我得到如下的Json数据。

[{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}]

我需要一个如下所示的输出,

[{"Name":"5","Data":"Immidiate"},
{"Name":"4","Data":"30 days"},
{"Name":"3","Data":"21 days"},
{"Name":"2","Data":"14 days"},
{"Name":"1","Data":"7 days"},
{"Name":"6","Data":"Custom"}]

这是我的代码

$rootScope.DashboardData["Name"] =  widget.seriesname ;
delete $rootScope.DashboardData[widget.seriesname];                
$rootScope.DashboardData["data"] =  widget.dataname ;
delete $rootScope.DashboardData[widget.seriesname];
widget.chartSeries = $rootScope.DashboardData;

其中widget.seriesname为“id”,widget.dataname为“name”。

问题:密钥未更改!

6 个答案:

答案 0 :(得分:7)

使用map功能:

var array = [{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}];

var resultArray = array.map(function(elm) {
   return { Name: elm[widget.seriesname], Data: elm[widget.dataname]};
});

答案 1 :(得分:2)

编辑:刚看到你的角标签 - 使用angular的forEach:

var out = [];

angular.forEach(data, function (obj) {
    out.push({
        Name: obj.id,
        Data: obj.name
    });
});

没有角度:

对于现代浏览器,请使用array.map:

var out = data.map(function (obj) {
   return {
        Name: obj.id,
        Data: obj.name
    };
});

console.log(out);

在旧版浏览器中:

var data = [{"id":"5","name":"Immidiate"},
           {"id":"4","name":"30 days"},
           {"id":"3","name":"21 days"},
           {"id":"2","name":"14 days"},
           {"id":"1","name":"7 days"},
           {"id":"6","name":"Custom"}];

var out = [];

for (var key in data) {
    if (data.hasOwnProperty(key)) {
        out.push({
            'Name': data[key].id,
            'Data': data[key].name
        });
    }
}

console.log(out);

答案 2 :(得分:2)

您还可以使用Underscopre.js map方法:

$scope.newList = _.map(list, function(item) {
 return { Name: item.id, Data: item.name};
});

参见 Fiddle

中的示例

答案 3 :(得分:0)

names: true
test: True

答案 4 :(得分:0)

public function updatePos(){
        $arrayloop = $this->input->post('position');
        foreach($arrayloop as $row){
            $data = array('packagePosition' => $row[1]);
            $this->db->where(array('packageId' => $row[0]));
            $this->db->update('package',$data);
        }
    }

答案 5 :(得分:0)

你也可以这样做:

arr.map(({id, name}) =>({name: id, data:name}))

const objArr = [
    { id: "5", name: "Immidiate" },
    { id: "4", name: "30 days" },
    { id: "3", name: "21 days" },
    { id: "2", name: "14 days" },
    { id: "1", name: "7 days" },
    { id: "6", name: "Custom" },
  ];

objArr.map(({id, name}) =>({name: id, data:name}))