所以我有服务器生成的以下javascript对象。该对象称为$ scope.activityResults
[{
id: 2010,
updateId: 1,
userId: 2,
points: 10
}, {
id: 2011,
updateId: 2,
userId: 3,
points: 100
}];
然后我有一个新创建的项目,我想确定userId是否存在于对象中。如果userId存在,我想做X,如果它们不存在我想做Y。
var newResult = {
id: 0,
updateId: 3,
userId: 10,
competitionId: "2014354864",
result: $scope.activityPointsValue,
time: new Date()
}
我正在努力找出检查userId是否已存在于对象中的最佳方式。
会爱一些帮助。
if (newResult.userId exists in $scope.activityResults)) { //This line needs the help :)
console.log("You already have some points");
} else {
console.log("Didnt find you, adding new row :)");
}
答案 0 :(得分:2)
最简单的方法是按用户ID索引scope.activityResults
数组。之后,这是一个简单的索引检查:
scope.activityResults[2] = {
id: 2010,
updateId: 1,
userId: 2,
points: 10
};
scope.activityResults[3] = {
id: 2011,
updateId: 2,
userId: 3,
points: 100
};
var newResult = {
id: 0,
updateId: 3,
userId:33,
competitionId: "2014354864",
result: scope.activityPointsValue,
time: new Date()
};
if (scope.activityResults.hasOwnProperty(newResult.userId)) { //This line needs the help :)
console.log("You already have some points");
} else {
console.log("Didnt find you, adding new row :)");
}
答案 1 :(得分:1)
试试这段代码:
var obj = [{
id: 2010,
updateId: 1,
userId: 2,
points: 10
}, {
id: 2011,
updateId: 2,
userId: 3,
points: 100
}];
console.log("Object:");
console.log(obj);
console.log("Check for User ID 5:");
console.log( userIdExists(5,obj) );
console.log("Check for User ID 3:");
console.log( userIdExists(3,obj) );
function userIdExists(uid, obj) {
for(i in obj)
if(uid == obj[i].userId) return true;
return false;
}
另外作为jsfiddle: http://jsfiddle.net/fygjw/
问候