所以我有服务器生成的以下 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 :)");
}
最佳答案
最简单的方法是按用户 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 :)");
}
关于javascript - 使用 Jquery 检查 Javascript 对象中是否存在某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629254/