我有一系列位置和嵌套用户对象,如下所示:
[
position: {
title: Developer,
user: { name: Albert }
},
position: {
title: CEO,
user: { name: Smith }
}
]
如何使用Angularjs获取[user,user]数组?
答案 0 :(得分:3)
假设这是伪代码(因为它缺少一些{
和}
,你需要变量名为Developer,Albert,CEO& Smith - I&# 39;已经在工作示例中修复了这些)你可以使用Array.map:
var arr = [{
Position0: {
title: Developer,
user: { name: Albert }
},
{
Position1 : {
title: CEO,
user: { name: Smith }
}
}];
var result = arr.map(function(val, idx) {
return val["Position" + idx].user.name;
});
答案 1 :(得分:2)
我刚试过这段代码,并且有效......
var positions, users;
users = [];
positions = [
{
title: 'Developer',
user: { name: 'Albert' }
},
{
title: 'CEO',
user: { name: 'Smith' }
}
];
angular.forEach(positions, function(position) {
users.push(position.user);
});
console.log(users);
答案 2 :(得分:1)
使用angular.forEach()
:
var arr1=[]
var arr=[
position: {
title: Developer,
user: { name: Albert }
},
position: {
title: CEO,
user: { name: Smith }
}
];
angular.forEach(arr,function(value,key){
arr1[key]=value.position.user;
});
console.log(arr1);
答案 3 :(得分:1)
首先,这件事不需要angularjs。
您可以这样做的方法是使用每个循环:
var users = [];
var positions = [{
Position0: {
title: 'Developer',
user: { name: 'Albert' }
},
Position1 : {
title: 'CEO',
user: { name: 'Smith' }
}
}]
for(var i =0; i< positions.length; i++){
for(var j in positions[i]){ //used to loop on object properties
if(positions[i].hasOwnProperty(j)){ //checking if the property is not inherited
if(positions[i][j].user){ //checking if the property exist, then only will push it to array, so that array doesnot have undefined values
users.push(positions[i][j].user);
}
}
}
}
用户数组将拥有用户。