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?

1
  • 1
    I fixed some obvious syntax errors. Commented Feb 4, 2014 at 22:52

2 Answers 2

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".

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

7 Comments

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.
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.
I'm getting the error 'cannot call method 'push' of undefined' for the this.info.push part
@cat-t: Pass this as second argument to .forEach: info.forEach(function (infoItem){...}, this). See also: stackoverflow.com/questions/20279484/…
@crush: A link to MDN would suffice IMO. People can find a polyfill there.
|
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!');

1 Comment

Setters are unnecessary here. This does nothing that can't be accomplished with Dependency Injection.

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.