2014-09-22 32 views
0

我有一些對象如何搜索數組內的對象屬性?

var arr = [{index: 1, type: 2, quantity: 1}, {index: 3, type: 1, quantity: 2}, {index: 1, type: 3, quantity: 3}]; 

現在我想,如果裏面存在一個對象與給定的指標和類型來搜索我的數組的數組。如果存在,我將數量屬性添加+1。如果不是,我添加一個數量爲1的新對象。我嘗試使用$ .grep和$ .inArray,但無濟於事。搜索對象數組中的屬性的最佳方法是什麼?

tnx!

+2

隨着['$ .grep()'](HTTP:// api.jquery.com/jQuery.grep/),函數需要返回條件的結果。關鍵字不是隱含的。 – 2014-09-22 18:03:03

+1

爲什麼不只是使用for循環條件? – Sergey6116 2014-09-22 18:10:37

+0

@true $ .grep比循環更聰明嗎?爲什麼?這不是更快。 – Sergey6116 2014-09-22 18:20:20

回答

1

在grep函數中,您需要返回測試結果,並且grep返回的結果也是一個新數組。它不修改現有的數組。

我製成一個片段:

var arr = [{index: 1, type: 2}, {index: 3, type: 1}, {index: 1, type: 3}]; 
 

 
var result = $.grep(arr, function(e){ 
 
    return e.index === 1 && e.type === 3 
 
}); 
 

 
alert(result[0].index + " " + result[0].type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2

For循環與如果條件:JsFiddle

var arr = [{index: 1, type: 2}, {index: 3, type: 1}]; 

var found = ''; 
for(item in arr){ 
    if(arr[item].index === 1 && arr[item].type === 2){ 
     found = arr[item]; 
    } 
} 
相關問題