1

I have a constructor function that serves to push new data to an array (in this case, allEntries)

function entry (title, info) {
    this.title = title;
    this.info = [ { name : info } ];
}
var allEntries = []

I'm trying to figure out how to pass multiple objects for this.info, something like:

allEntries.push( new entry( 'title one', ['info 1', 'info 2'] ) );

in order to obtain something like:

{
    title: 'title one', 
    info : [
            { name: 'info 1'},
            { name: 'info 2'}
        ]
}

How would I go about doing this?

crush
  • 16,713
  • 9
  • 59
  • 100
cat-t
  • 1,346
  • 1
  • 18
  • 34

2 Answers2

2

Pass an array and iterate over it to add all items using Array.prototype.forEach.

function entry (title, info) {
    this.title = title;
    this.info = [];
    info.forEach(function (infoItem) {
        this.info.push({ name : infoItem});
    }, this);
}

Call it like this:

var myEntry = new entry('foobar', ['info1', 'info2']);

BTW: Usually, classes are named with an uppercase letter in front to be able to distinguish them from functions (which are always lowercase), so you migth want to name it "Entry".

Johannes H.
  • 5,875
  • 1
  • 20
  • 40
  • Mind me to disagree? if `info` is an array of strings, and `this.info` should be an array of objects that have the string stored in an attribute called `name`, than yes, there is. – Johannes H. Feb 04 '14 at 22:55
  • You're right. I overlooked the fact that he wants to pass an array of strings, and that get turned into an array of objects with `name` as the property, and the string as the value. – crush Feb 04 '14 at 22:56
  • I'm getting the error 'cannot call method 'push' of undefined' for the this.info.push part – cat-t Feb 04 '14 at 22:57
  • 2
    @cat-t: Pass `this` as second argument to `.forEach`: `info.forEach(function (infoItem){...}, this)`. See also: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – Felix Kling Feb 04 '14 at 22:58
  • @FelixKling That's a better solution. Should he add a warning about the browser support for `Array.forEach`? – crush Feb 04 '14 at 22:58
  • 2
    @crush: A link to MDN would suffice IMO. People can find a polyfill there. – Felix Kling Feb 04 '14 at 22:59
  • Thanks Johannes, your answer was just what I was looking for, +1 – cat-t Feb 04 '14 at 23:13
0

This can be solved by approaching it differently...

http://jsfiddle.net/MattLo/Nz6BD/

function entry () {
    this.title = null;
    this.info = [];
}

entry.prototype.setInfo = function (info) {
    this.info.push({name: info});

    return this;
};

entry.prototype.setTitle = function (title) {
    this.title = title;

    return this;
}

var e1 = (new entry)
    .setInfo('foo')
    .setInfo('bar')
    .setTitle('Hello World!');
Matt Lo
  • 5,442
  • 1
  • 21
  • 21
  • Setters are unnecessary here. This does nothing that can't be accomplished with Dependency Injection. – crush Feb 04 '14 at 22:53