javascript - 使用 Jquery 检查 Javascript 对象中是否存在某些内容

标签 javascript jquery angularjs angularjs-scope

所以我有服务器生成的以下 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/

相关文章:

javascript - d3js/AngularJS - 在 Angular Directive(指令)中使用 d3js

javascript - 使用 key 更新 Firebase 数据,为什么要插入新对象

javascript - 缩小尺寸时如何将标签更改为下拉列表?

jQuery 滚动到 iOS 地址栏顶部

javascript - 如何在 Angular js $http 调用中显示超时错误?

javascript - Angular HTTP promise 返回空

javascript - 如何使用 JQuery 设置多组 .on() 输入 slider 的输出目标?

javascript - 即使confirm()方法为false,Jquery AJAX也会提交表单

javascript - 不同的框有不同的复选框

php - AJAX POST 到 PHP mySQL 查询