I have an object:
var obj = {'a':true,'b':false,'c':false,'d':true}
and I have a synced array which contains keys whose values are true in the object.
var arr = ['a','d']
So if obj changes to following: (a's value changed to false)
obj = {'a':false,'b':false,'c':false,'d':true}
Then arr should be synced to following: (a element gets removed from arr)
arr = ['d'];
I have thought of two solutions:
Whenever object changes, I manipulate the same arr by performing push/remove operation on that key in array depending on the value of the key in object. (Updates to the object can be easily detected using angularjs in my case)
Whenever object changes, I will replace old array with new array containing only those keys whose value is set to true in.
Which solution is better??
Live demo:
You could use a simple class:
function Pair(obj, arr) {
this.obj_ = obj || {};
this.arr_ = arr || [];
this.updateArray();
};
Pair.prototype.set = function(key, val) {
this.obj_[key] = val;
this.updateArray();
};
Pair.prototype.updateArray = function() {
this.arr_.length = 0;
for (var key in this.obj_) {
if (this.obj_.hasOwnProperty(key)) {
if (this.obj_[key] === true) {
this.arr_.push(key);
};
};
};
};
Pair.prototype.getArray = function() {
return JSON.stringify(this.arr_);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With