Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sync object with an array

Tags:

javascript

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:

  1. 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)

  2. 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??

like image 340
anshul Avatar asked Jun 08 '26 16:06

anshul


1 Answers

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_);
};
like image 110
flavian Avatar answered Jun 10 '26 06:06

flavian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!