Reputation: 709
I have an array with some objects
var arr = [{index: 1, type: 2, quantity: 1}, {index: 3, type: 1, quantity: 2}, {index: 1, type: 3, quantity: 3}];
Now I want to search my array if exists an object inside it with a given index and type. If exists, I add + 1 to the quantity property. If not, I add a new object with quantity of 1. I tried to use, $.grep and $.inArray but to no avail. What is the best way to search the properties in an array of objects?
tnx!
Upvotes: 0
Views: 58
Reputation: 1198
In the function in grep you need to return the result of the test and also the result returned from grep is a new array. It does not modify the existing array.
I made a snippet:
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>
Upvotes: 1
Reputation: 124
For loop with if condition: 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];
}
}
Upvotes: 2