简体   繁体   English

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

[英]Checking whether something exists in a Javascript object with Jquery

So I have the following javascript object generated by the server. 因此,我具有服务器生成的以下javascript对象。 The object is called $scope.activityResults 该对象称为$ scope.activityResults

        [{
            id: 2010,
            updateId: 1,
            userId: 2,
            points: 10
        }, {
            id: 2011,
            updateId: 2,
            userId: 3,
            points: 100
        }];

I then have a newly created item, and I want to determine whether the userId exists in the object or not. 然后,我有一个新创建的项目,我想确定userId是否存在于对象中。 If the userId exists, I want to do X, if they don't exist I want to do Y. 如果userId存在,我想做X,如果它们不存在,我想做Y。

var newResult = {
            id: 0,
            updateId: 3,
            userId: 10,
            competitionId: "2014354864",
            result: $scope.activityPointsValue, 
            time: new Date()
        }

I'm struggling to figure out the best way to check whether the userId already exists in the object or not . 我正在努力找出检查userId是否已存在于对象中的最佳方法。

Would LOVE some help. 需要一些帮助。

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 :)");
        }

Easiest way would be to index the scope.activityResults Array by user id. 最简单的方法是按用户ID索引scope.activityResults数组。 After that it's a simple index check: 之后,这是一个简单的索引检查:

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 :)");
}

Try this code: 试试这个代码:

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;
}

Also as jsfiddle: http://jsfiddle.net/fygjw/ 也作为jsfiddle: http//jsfiddle.net/fygjw/

greetings 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM