0

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

Pradeep Mahdevu
  • 7,613
  • 2
  • 31
  • 29

3 Answers3

1

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.

Community
  • 1
  • 1
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

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();
fast
  • 885
  • 7
  • 15
  • The only thing with this approach is that it changes the reference of the objects. – Pradeep Mahdevu Jun 13 '14 at 12:41
  • @PradeepMahdevu With this approach, changes to 'values' actually are reflected in 'original'. – fast Jun 13 '14 at 12:49
  • When you are calling getValues() each time, you are returning a new array. So the array is a new ref every time. you can get away with that, values = values || []; values.length = 0; – Pradeep Mahdevu Jun 13 '14 at 12:54
0

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.

Christian Rondeau
  • 4,143
  • 5
  • 28
  • 46