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

问题描述 投票:2回答:4

在我的角度应用程序中,我得到如下的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”。

问题:密钥没有改变!

javascript json angularjs html5
4个回答
8
投票

使用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]};
});

2
投票

你也可以使用Underscopre.js map方法:

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

参见Fiddle中的示例



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);

0
投票
const arr = [{"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"}];

const resultArray = arr.map(elm => ({ Name: elm.id, Data: elm.name}));

console.log(resultArray);
© www.soinside.com 2019 - 2024. All rights reserved.