I am trying to build an object in JavaScript, but have properties updated or created based on if a product id already exists. I have:
var model = [];
$('.glyphicon-plus').click(function() {
var product_id = $('#productSelect').val();
var size_id = $('#sizeSelect').val();
var colour_id = $('#colourSelect').val();
var quantity = $('#quantity').val();
if (i = subFilter(model, "product_id", product_id) !== false) {
if (i = subFilter(model, "size_id", size_id) !== false) {
if (i = subFilter(model, "colour_id", colour_id) !== false) {
console.log(model);
model.i.quantity = quantity;
}
}
}
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
subFilter(model, "product_id", product_id);
console.log(model)
});
function subFilter(object, paramName, paramValue) {
$.each(object, function(i, v) {
if (v[paramName] == paramValue) {
return i;
}
});
}
But I am getting:
Uncaught TypeError: Cannot set property 'quantity' of undefined
How can I build up this object properly, inserting a new "record" or updating if it already exists?
subFilterfunction is doing what you think it's doing, I would check the value ofiafter it's first assignment if I were you. Also, no matter what,subFilterwill never be=== falseso the if statements will always pass even if they shouldn't