10

I want to set string properties on my array.

E.g.

function readInput (arr) {
  var data = db.query('something');
  arr.itemType = data.itemType; // -> This
  arr.push.apply(arr, data.list);
}

var myArr = [];
readInput(myArr);

The idea is to store some meta-data on the array itself.

Is this a good approach? Am I creating any problems by doing this?

  • 1
    Code that iterates over the array with a `for...in` loop will probably not work as expected. But then again, you should not iterate over an array with `for...in`. In the end, arrays are just objects, so you can do whatever you want ;) – Felix Kling Jul 14 '14 at 05:45
  • 2
    You’ll just have to use your best judgement. Does it look clear? Does it make sense for the property to belong on the array? If it does, feel free. – Ry- Jul 14 '14 at 05:45
  • Is there a reason you don't want to store the array in an object, with the other properties of the object being the "metadata" about the array? – drewblaisdell Jul 14 '14 at 05:47
  • @drewblaisdell, I wouldn't mind doing that. That's when this struck me. Why not set the meta-data on the array itself? I've not seen this style anywhere. – Sachin Hosmani Jul 14 '14 at 05:49
  • Do you think I should delete the question? Now I feel this might be a `best practice` question which probably isn't encouraged here. – Sachin Hosmani Jul 14 '14 at 05:50
  • I think there is nothing wrong with adding metadata to an array as long as you use a namespace. By using this method you'd be able to still use Array methods like map, filter, reduce which is a plus – Ouwen Huang Jul 14 '14 at 05:54
  • 4
    Nothing in the language expects this, including Array's own functions. If you duplicate or transform the array in some way, so that a new array is returned (`map`, `concat`, `slice`, etc), you'll be stripping away all the non-standard properties you've added to it. You should treat arrays like dumb data storage, and if you want to store additional meta data about the array, create a wrapper class. – user229044 Jul 14 '14 at 06:02
  • Related: [Add property to javascript array](http://stackoverflow.com/questions/9952126/add-property-to-javascript-array). – Ja͢ck Jul 14 '14 at 07:13

1 Answers1

5

I agree with meagar's comment above.

It doesn't make sense to add unexpected properties to the existing data structure. For example, cloning the array ignores any invalid properties of the original array and the "meta data" is not preserved:

var arr = [1, 2, 3, 4],
    newArr = [];

arr.metaSomething = "uhoh!";

newArr = arr.slice(0);

newArr.metaSomething; // undefined

Because this is an unexpected behavior (as in, it's probably not what you would like to happen), it would probably be better to store the information in an object, since that's what you are treating the array like anyway.

Dave
  • 723
  • 7
  • 19