我可以获得一个JSON对象数组
[
{
Id: "1",
StartNo: "1",
ChipNo: "0",
CategoryId: "0",
Wave: "0",
Club: "",
FirstName: "Lotta",
LastName: "Svenström",
FullName: "Lotta Svenström",
ZipCode: "24231"
},
{...}
]
我想创建一个仅包含StartNo和FullName的新数据结构。我如何实现这一目标?
我试过了:
$scope.runners = [];
for(var i = 0; i<data.length; i++){
$scope.runners[i].StartNo = data[i].StartNo;
$scope.runners[i].Fullname = data[i].Fullname;
}
但这不起作用。
答案 0 :(得分:1)
您只能使用以下两个属性创建新对象:
for (var i = 0; i < $scope.runners.length; i++){
$scope.runners[i] = {
StartNo: data[i].StartNo,
Fullname: data[i].Fullname
}
}
或者,如果您需要保留引用,请从对象中删除所有其他属性:
for (var i = 0; i < $scope.runners.length; i++){
for (var k in $scope.runners[i]) {
if ($scope.runners[i].hasOwnProperty(k) && k !== 'StartNo' && k !== 'Fullname') {
delete($scope.runners[i][k]);
}
}
}
答案 1 :(得分:1)
使用map
- Array
的功能:
var data = [...your JSON objects...];
$scope.runners = data.map(function(runner) {
return {
StartNo: runner.StartNo,
Fullname: runner.Fullname
};
});
答案 2 :(得分:1)
您可以使用本地map
,如下文
var $scope.runners = data.map(function(obj){
return {StartNo:obj.StartNo,FullName:obj.FullName};
});
答案 3 :(得分:1)
试试这段代码
var data=[
{
Id: "1",
StartNo: "1",
ChipNo: "0",
CategoryId: "0",
Wave: "0",
Club: "",
FirstName: "Lotta",
LastName: "Svenström",
FullName: "Lotta Svenström",
ZipCode: "24231"
}
];
var runners =[];
for(var i = 0; i<data.length; i++){
runners[i]={};
runners[i].StartNo = data[i].StartNo;
runners[i].Fullname = data[i].Fullname;
}
答案 4 :(得分:1)
$scope.runners=[];
$scope.sampleRunner = [
{
Id: "1",
StartNo: "1",
ChipNo: "0",
CategoryId: "0",
Wave: "0",
Club: "",
FirstName: "Lotta",
LastName: "Svenström",
FullName: "Lotta Svenström",
ZipCode: "24231"
},
{
Id: "1",
StartNo: "2",
ChipNo: "0",
CategoryId: "0",
Wave: "0",
Club: "",
FirstName: "Lotta",
LastName: "Svenström",
FullName: "Velu",
ZipCode: "24231"
},];
angular.forEach($scope.sampleRunner, function (data) {
$scope.runners.push({ StartNo: data.StartNo, FullName: data.FullName });
});