0

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;
},
8
  • If you can use a library, i suggest you to test lodash: lodash.com It can help you working with arrays, collections and objects. Commented Jul 31, 2017 at 9:20
  • 1
    I disagree, LoDash becomes pretty much useless when you master .filter, .map and other pretty powerful methods JS arrays have out of the box. Commented Jul 31, 2017 at 9:21
  • i dont understand what you are trying to do. Do you want to add something to the object in the array, or do you want to add in the array? Commented Jul 31, 2017 at 9:21
  • @KristjanKica add to array Commented Jul 31, 2017 at 9:22
  • use push perhaps? Commented Jul 31, 2017 at 9:22

1 Answer 1

1

You can use findIndex() to check if object with same id exists in array and if it does replace it with new object or if it doesn't push new object to array.

var arr = [
  {id: 1, name: "john"},
  {id: 2, name: "Sam"}
]

function addOrReplace(data, obj) {
  var i = data.findIndex(function(e) {
    return e.id == obj.id;
  });

  i != -1 ? data[i] = obj : data.push(obj);
  return data;
}

console.log(addOrReplace(arr, {id: 1, name: "lorem"}))
console.log(addOrReplace(arr, {id: 3, name: "ipsum"}))

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please show this var i = data.findIndex(e => e.id == obj.id); in simple js
Thanks for introducing findIndex() but what is wrong with my hashing function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.