2014-09-22 33 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]; 
    } 
} 
相关问题