最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript sync object with an array - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Jun 21, 2013 at 7:32 anshul asked Jun 21, 2013 at 7:15 anshulanshul 315 bronze badges 2
  • 7 This is an interesting problem, but in practice do you really want to be doing something like this? Seems very error-prone. Keep each fact in one place. You can store the object only and then write a function to return an array containing only the keys that have a value that is true. – Ray Toal Commented Jun 21, 2013 at 7:19
  • Option 2 should be easier (and less error prone). Unless you have thousands of properties in your object, option 2 should be the way to go. – techfoobar Commented Jun 21, 2013 at 7:22
Add a ment  | 

5 Answers 5

Reset to default 2

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_);
};

I do not think that managing an external array is a practical solution. The array you are searching for represents a status of the object. So I suggest to add a method to the object that dynamically returns an array of properties based on their values:

var obj = {'a':true,'b':false,'c':false,'d':true};

obj.getPropertiesByState = function(state){
  var res = [];
  for (var key in this) {
    if (this[key] === state) {
      res.push(key);
    }
  }
  return res;
}

var trueProperties = obj.getPropertiesByState (true);

Well it depends on few things.

How many pairs you have in an object or how many such such objects you have.

Can you depict in brief your use case?

First one is less memory efficient as you are relying on GC. But its less error prone.

So if you have less items(say 50 or 100 may be) in an object than replacing the array(building the new array) should be better.

At times, Less error-prone code is better than less memory efficient code.

You mentioned you are using angular, this might help you straight away if you are looking for code solution.

$scope.$watch('obj', function (newVal, oldVal) {
    $scope.selectedItems = $.map(newVal,function(k,v){
      if(k === true)
        return v;
    });
  },true);

jQuery's map function should be what you need.

var o = {'a':true,'b':false,'c':false,'d':true};

jQuery.map(o, function(val, idx){
  if(val)
   return idx;
});

if an Object changes, you could replace the old array with this: Still I don't think this is a pretty good solution..

First one is better. In this case you need to remove only those whose values has been changed.

e.g. We have 1000 thousands elements in an array. But only one is changed. So it will only execute for one element.

In your second case, it will check all the elements i.e time consuming and processing.

发布评论

评论列表(0)

  1. 暂无评论