0

1st observable array:

data = [{id:1 , name:'abc'},{id:2 ,name:'xyz'},{id:3 , name:'rst'}]

another array:

dataProvider = [{id:3 , name:'pqr'} , {id:4 , name:'hjk'}]

Now can we compare the data array with data provider and for id = 3 it should replace the previous object and with id = 4 it simply push the object into data array.

Therefore the new data array will something like this

data = [{id:1 , name:'abc'},{id:2 ,name:'xyz'} ,{id:3 , name:'pqr'} , {id:4 , name:'hjk'}]   
xyz
  • 405
  • 1
  • 6
  • 19
  • Try changing your `for..in` to a `for` loop, or check `hasOwnProperty` if you must use `for..in`. See [this question](http://stackoverflow.com/questions/242841/javascript-for-in-vs-for). (Not sure if it fixes your issue, but it can't hurt either.) – Jeroen May 21 '13 at 09:37

2 Answers2

0

Yes, you can :

$.each(self.data(), function() {
    for (var x in dataprovider) {
       if (this.id === x.id)
          this.data = x.data;
       else {
          self.data().push({id: x.id, data: x.data});
       }
    }
});

Knockout.js is a library fully integrated with jQuery.

cat916
  • 1,363
  • 10
  • 18
  • What in case when dataprovider is also an array and can contain any number of objects – xyz May 21 '13 at 12:06
  • thanks for edit @minhcat but my mistake is I have not mention the question properly. But now I have Edited it. Can you help me out in this case. – xyz May 21 '13 at 12:18
0

An alternative to using $.each would be to use knockout's own utility function ko.utils.arrayFilter to achieve this. I also cached the matchable Ids in an object so that we don't have to loop over the entire dataprovider for each data entry.

var matches = {},
    i = 0,
    len = dataprovider.length,
    filteredData = [];

// transform data to prevent looping over array n times where n = data.length
for (; i < len; i++) {
    matches[dataprovider[i].id] = dataprovider[i];
}

filteredData = ko.utils.arrayFilter(self.data(), function(item) {
    return !(item.id in matches); // leave the item out if its in the dataprovider
});

self.data(filteredData.concat(dataprovider)); // merge in all of the dataprovider results
GotDibbs
  • 3,068
  • 1
  • 23
  • 29