views:

66

answers:

3

Is there a way to specify common elements for object literals in an array?

For example:

var array = [ {key: "hi", label: "Hi", formatter:deleteCheckboxFormatter},
              {key: "hello", label: "Hello", formatter:deleteCheckboxFormatter},
              {key: "wut", label: "What?", formatter:deleteCheckboxFormatter}];

All three records use the same formatter. How would you refactor this?

A: 
var array = [ {key: "hi", label: "Hi"},
              {key: "hello", label: "Hello"},
              {key: "wut", label: "What?"}];

for(var item in array)
  item["formatter"] = deleteCheckboxFormatter;
Amarghosh
+3  A: 

A pair of alternatives come to my mind:

A helper function with the default value for the common field:

function make(key, label) {
  return {'key': key, 'label': label, formatter:deleteCheckboxFormatter};
}

var array = [ make("hi",  "Hi"),
              make("hello", "Hello"),
              make("wut", "What?")];

Or a more generic function that accepts an argument for the formatter property:

function make (formatter) {
  return function (key, label) {
    return {'key': key, 'label': label, 'formatter':formatter};
  }
}

// a function to build objects that will have a 'fooFormatter'
var foo = make('fooFormatter'); 

var array = [ foo ("hi",  "Hi"),
              foo ("hello", "Hello"),
              foo ("wut", "What?")];

And the last thing that comes to my mind is simply iterate over the array assigning the common field:

var array = [ {key: "hi", label: "Hi"},
              {key: "hello", label: "Hello"},
              {key: "wut", label: "What?"}];

var i = array.length;
while (i--) {
  array[i].formatter = 'deleteCheckboxFormatter';
}

I used here a while loop in reverse order, because the order of iteration is not important and this type of loop performs better.

CMS
+1 for going way beyond the call of duty. Personally, I'd go with the first or second option
Jonathan Fingland
A: 

You could make an object out of it using a constructor:

function Obj(key, label){
  this.key = key;
  this.label = label;
  this.formatter = "deleteCheckboxFormatter";
}
var array = [ new Obj("hi", "Hi"),
              new Obj("hello", "Hello"),
              new Obj("wut", "What?") ];
Marius