2

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 :)");
        }
2
  • jQuery will not help you here. Commented Feb 7, 2014 at 13:45
  • Ah really, what will ? :=) Commented Feb 7, 2014 at 13:47

2 Answers 2

2

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 :)");
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.