Currently facing a challenging problem and in search of an efficient solution.
I have two Javascript Objects structured as {id:data, id:data, ..}
If we focus solely on the Keys, they appear like this:
B = ["1","2","3"]
A = ["2","3","4"]
My goal is to figure out how to transform B into A. For instance, Delete B.1 and B.4 so that it matches A.4 .
I've been contemplating whether creating a prototypal function for Object would be a viable approach.
This is my current implementation:
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
Object.prototype.syncTo = function(b,callbackA,callbackB){
var a = this;
var bKeys = Object.keys(b);
var aKeys = Object.keys(a);
var toremove = bKeys.diff(aKeys);
var toadd = aKeys.diff(bKeys);
for(var i = 0; i < toremove.length; i++) {
if(b.hasOwnProperty(toremove[i])) {
delete b[toremove[i]];
}
}
callbackB(b);
for(var i = 0; i < toadd.length; i++) {
if(a.hasOwnProperty(toadd[i])){
<<Struggling with next steps>>
}
}
callbackA(XXXXXX);
};
The idea behind CallbackA is to add elements to B, while CallbackB involves removing elements from B based on the transformation needed.
Currently grappling with determining the elements for callbackA and evaluating the efficiency of this process.
Appreciate your guidance and assistance!
EDIT: An example callback could be :
callbackB:
function (items){
for(var i in items){
items[i].removeSomeWhereElse();
}
}