Inheriting Javascript Properties

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 entries use the same formatter. How would you reorganize this?

+3
source share
3 answers

A couple of alternatives come to my mind:

Helper function with default value for 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 general function that takes 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 to simply iterate over an array that assigns a 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 the while loop here in the reverse order, because the iteration order is not important, and this type of loop works better .

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

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

:

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

Source: https://habr.com/ru/post/1720432/


All Articles