How do I add or replace into existing array of objects. Lets say I have existing array like this:
productOffer.view = [
{id: 1, name: "john"},
{id: 2, name: "Sam"}
]
productOffer.view.forEach(function(el,i){
if(el.id == productOffer.createId){
productOffer.view[i] = ajaxCall.responseJSON
} else {
productOffer.view.push(ajaxCall.responseJSON);
}
});
Tried the following but the values are getting replaced instead of adding:
productOffer.hashedArr = productOffer.hash(productOffer.view);
productOffer.view.forEach(function(el,i){
if(el.id == productOffer.createId){
productOffer.hashedArr[i] = ajaxCall.responseJSON
} else {
productOffer.hashedArr[i] = el;
}
});
for(var key in productOffer.hashedArr){
productOffer.view = [];
productOffer.view.push(productOffer.hashedArr[key]);
}
hash: function(arr){
var arrIndex = Object.create(null);
arr.forEach(function(el){
arrIndex[el.id] = el;
});
console.log('hash ', arrIndex);
return arrIndex;
},
.filter,.mapand other pretty powerful methods JS arrays have out of the box.