Reputation: 970
I have the following scenario where my parameter array contains two arrays
<script>
var parameter = [];
var brand;
var category = [];
$(function() {
$('#brand_category').click(function(event){
var newhtml="";
var Html = "";
var cat_li = "";
var $table = $('table#tablerow')
var added = "";
if($('input[name=brand]:checked').length<=0)
{
alert("Please Select brand")
}
if($('input[name=category]:checked').length<=0) {
alert("Please Select Category")
}
else {
cat = $("input:checkbox[name=category]:checked").map(function() {
return this.value;
}).get();
br = $("input[type='radio']:checked").map(function() {
return this.value;
}).get();
var found = jQuery.inArray(br, parameter);
console.log(found)
parameter.push({
brand : br,
category: cat,
});
});
</script>
the parameter dictionary looks like this
Array[2]
0: Object
brand: Array[1]
0: "spykar"
length: 1
__proto__: Array[0]
category: Array[1]
0: "Men Jeans"
length: 1
__proto__: Array[0]
__proto__: Object
1: Object
brand: Array[1]
0: "Madame"
length: 1
__proto__: Array[0]
category: Array[1]
__proto__: Object
length: 2
__proto__: Array[0]
I want to push to parameter if the value doesnt exists and if it exists then it should not push.I tried to use inArray() but it always returns -1.What can be the problem . What i want here is if the category is not already present then it should add to corresponding brand object.If present then it should not.similarly no two brands should be present
Upvotes: 1
Views: 8780
Reputation: 408
Simple Solution ::
var parameter = [];
cat = $("input:checkbox[name=category]:checked").map(function() {
return this.value;
}).get();
br = $("input[type='radio']:checked").map(function() {
return this.value;
}).get();
$.map(parameter, function(elementOfArray, indexInArray) {
if (elementOfArray.brand == br) {
console.log('true');//do what you need on found
parameter.push({
brand : br,
category: cat
});
}else{
console.log('false');//do what you need on not found
}
});
ref :: this link
Upvotes: 0
Reputation: 970
i tried this solution after reading some answers
$.map(parameter, function(elementOfArray, indexInArray) {
for (var key in elementOfArray.brand) {
if (elementOfArray.brand.hasOwnProperty(key)) {
if (elementOfArray.brand[key] == br) {
added = true
}
}
}
});
console.log(added);
if (!added) {
parameter.push({
brand : br,
category: cat
});
Upvotes: 1
Reputation: 2022
Because you aren't pushing just the value of br
, you're pushing the values of br
and cat
as an object, you can't directly compare them using inArray()
For this to work, you will need to loop through parameter
and test the value of each object inside it against br
var found = -1;
for (i=0;i<parameter.length;i++){
if (parameter[i].brand == br) {
found = i;
}
}
if (found < 0){
parameter.push({
brand: br,
category: cat
});
}
Upvotes: 1