2014-02-07 59 views
2

所以我有以下由服務器生成的javascript對象。該對象被稱爲$ scope.activityResults使用Jquery檢查是否存在某個Javascript對象

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

然後我有一個新建項目,我想,以確定用戶id是否存在於物體與否。如果用戶標識存在,我想要做X,如果不存在,我想這樣做Y.

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

我掙扎的最佳途徑找出該檢查用戶id是否已經存在於對象與否

會喜歡一些幫助。

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

'x'in newResult – JAYBEkster

+0

jQuery不會幫你在這裏。 – Bergi

+0

真的啊,會怎麼樣? :=) – user2656127

回答

2

最簡單的方法是將指數scope.activityResults陣列的用戶ID。之後,這是一個簡單的索引檢查:

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

完美,謝謝! – user2656127

1

試試這個代碼:

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/

問候