在我的角度应用程序中,我得到如下的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”。
问题:密钥没有改变!
使用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]};
});
你也可以使用Underscopre.js map
方法:
$scope.newList = _.map(list, function(item) {
return { Name: item.id, Data: item.name};
});
参见Fiddle中的示例
编辑:刚看到你的角标签 - 使用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);
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);