2014-04-28 60 views
0

我遇到了一個問題,試圖查看一個值是否與包含一個對象的數組相匹配。查找對象內的值 - jQuery

下面是我在做什麼:

var found = $.inArray(opt.ifpo_width, selectedOptions) > -1; 

比方說opt.ifpo.width包含650selectedOptions包含一個值爲650的對象,因此我希望found返回0,因爲這意味着該值已找到。

繼承人的selectedOptionsconsole.log一個例子:

[Object, Object] 
0: Object 
active: true 
...... 
ifpo_width: "650" <-- value I am checking 
ifpo_x: "153" 
ifpo_y: "86" 
shown: false 
__proto__: Object 
1: Object 
active: true 
ifpo_width: "650" <-- this other object should not be here because there is already a width of the same value. 
ifpo_x: "140" 
ifpo_y: "102" 
..... 

你有什麼建議和如何我可以檢查此selectedOptions的價值與opt.ifpo_width被檢查的想法?

回答

1

如果ifpo_width可以改變,你可以使用函數一樣,

function search(property, arr, value) { 
     var t; 
     for (t = 0; t < arr.length; t++) { 
      if (arr[t][property] == value) 
       return true; 
     } 

     return false; 
    } 

,並把它

search("ifpo_width", YourArray, selectedOptions) 

否則,更加簡單

function search(arr, value) { 
     var t; 
     for (t = 0; t < arr.length; t++) { 
      if (arr[t].ifpo_width == value) 
       return true; 
     } 

     return false; 
    }