[英]How do i access nested array values in angular.js?
我想訪問另一個數組內部的數組中存在的對象,如下所示。
{
"_id": ObjectId("574d2aa42ec356541dc7034e"),
"contributedProductName": "ITOS365 Radha Krishna Brass Statue Hindu God Sculpture Religious Gifts Item, 5.5 Inches",
"contributedProductId": "57459ef82b01e7802ca9294b",
"receiverId": "570dec75cf30bf4c09679deb",
"contributorDetails": [
{
"name": "Hemanth",
"email": "hemanth@gmail.com",
"amount": "500"
},
{
"name": "Kevin",
"email": "kevinguru888@gmail.com",
"amount": "300"
},
{
"name": "vinay",
"email": "vinay@gmail.com",
"amount": "149"
}
]
}
現在,我想訪問contributorDetails數組中存在的單個對象,但是我只獲得該數組中的最后一個對象。 我已經嘗試過以下在angular.js控制器中。
function ManageContributorController($http, $location, $rootScope, $localStorage)
{
var vm = this;
vm.uid = $localStorage._id;
//console.log(vm.uid);
$http({
url: 'http://192.168.2.8:7200/api/manage-contributor',
method: 'POST',
data: {userId:vm.uid}
}).success(function(res) {
for(var key in res.result){
for(var anotherKey in res.result[key].contributorDetails){
var cName = res.result[key].contributorDetails[anotherKey].name;
var cEmail = res.result[key].contributorDetails[anotherKey].email;
var cAmnt = res.result[key].contributorDetails[anotherKey].amount;
}
res.result[key]['contributorName']=cName;
res.result[key]['contributorEmail']=cEmail;
res.result[key]['contributedAmount']=cAmnt;
}
vm.result = res.result;
console.log(vm.result);
}, function(error) {
console.log(error);
alert('here');
});
}
contributorDetails是對象元素內的數組。 試試這個
obj.contributorDetails[i].name, //i is the index if you know the index you want to access
//or get them all
for (var i = 0 ; i < obj.contributorDetails.length; i++)
{
obj.contributorDetails[i].name
obj.contributorDetails[i].email
obj.contributorDetails[i].amount
} //in your case, obj = res.result;
contributorDetails
是一個json數組
您可以這樣訪問
res.contributorDetails.forEach(function(item){
document.write('<pre>'+item.name + ' -- '+ item.email+'</pre>'+'</br>')
})
試試下面的東西
vm.result = [];
function(res) {
for(var key in res.result){
for(var anotherKey in res.result[key].contributorDetails){
var cName = res.result[key].contributorDetails[anotherKey].name;
var cEmail = res.result[key].contributorDetails[anotherKey].email;
var cAmnt = res.result[key].contributorDetails[anotherKey].amount;
}
res.result[key]['contributorName']=cName;
res.result[key]['contributorEmail']=cEmail;
res.result[key]['contributedAmount']=cAmnt;
vm.result.push(res.result[key); //Push into the array
}
console.log(vm.result);
}
希望這會有所幫助。
嘗試angular.forEach(假設您的對象名稱為$ scope.obj):
angular.forEach($scope.obj.contributorDetails, function(item){
//each item is an individual object, to access individual values you can do this:
//item.name
//item.email
//item.amount
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.