简体   繁体   中英

Checking whether something exists in a Javascript object with Jquery

So I have the following javascript object generated by the server. The object is called $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. If the userId exists, I want to do X, if they don't exist I want to do 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 .

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. 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/

greetings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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