簡體   English   中英

使用Jquery檢查Javascript對象中是否存在某些內容

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

因此,我具有服務器生成的以下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 :)");
}

試試這個代碼:

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

也作為jsfiddle: http//jsfiddle.net/fygjw/

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM