Pradeep Mahdevu
Pradeep Mahdevu

Reputation: 7663

Object values to array but with same reference

I have an object with dynamic properties. Each of these properties are removed and added based on some events. I want to have a function or property in this object which can return the array of values but having the same reference all the time. Whats the best way to do it?

For e.g if current state of the object is

var obj = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} }
var values = obj.someFunction()

values should be [{ 'name' : 'dark'}]

if current state of obj is

{"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}}

values should be [{ 'name' : 'dark'},{ 'name' : 'magic'}]

The reference of the array and the properties should never change (unless they are deleted).

Upvotes: 0

Views: 170

Answers (3)

fast
fast

Reputation: 885

My might create a 'meta'-object that stores a reference to the original object and can return the values:

var Values = function(obj) {

 this.getValues = function() {

  var values = [];
  for(i in obj)
   values.push(obj[i]);
  return values;
 };

}

var original = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
                "f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}};

var vals = new Values(original);

var values = vals.getValues();

Upvotes: 1

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

How about this? It maintains the same array. If you want, you could also mix it in with the object, but would have to add a guard to not also add the function to the values.

var values = someFunction(obj, values);

function someFunction(obj, values) {
    values = values || [];
    values.length = 0;

    for(var key in obj) {
        values.push(obj[key]);
    }

    return values;
}

By the way, clearing the array by setting its length to 0 was gleaned from this post.

Upvotes: 1

Christian Rondeau
Christian Rondeau

Reputation: 4603

Given that you seem to be generating the array within "someFunction" (seeing the code of the function and how you attach it to the object would help), you'll need to keep an instance of an array and empty/refill it rather than create a new one. It could be a member of your object (obj.currentItems) or within a closure (depending on how you create it), and it could be updated as you change its properties or on demand within someFunction.

I'll update my answer if you provide more specific code.

Upvotes: 0

Related Questions