我想访问另一个数组中数组中存在的对象,如下所示。
{
"_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');
});
}
答案 0 :(得分:0)
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;
答案 1 :(得分:0)
contributorDetails
是一个json数组
你可以像这样访问它
res.contributorDetails.forEach(function(item){
document.write('<pre>'+item.name + ' -- '+ item.email+'</pre>'+'</br>')
})
答案 2 :(得分:0)
尝试以下内容
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);
}
希望这会有所帮助。
答案 3 :(得分:0)
尝试使用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
});