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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for going way beyond the call of duty. Personally, I'd go with the first or second option
0
var array = [ {key: "hi", label: "Hi"},
              {key: "hello", label: "Hello"},
              {key: "wut", label: "What?"}];

for(var item in array)
  item["formatter"] = deleteCheckboxFormatter;

Comments

0

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?") ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.