sbeliakov
sbeliakov

Reputation: 2199

Is it possible to iterate through top-level array in underscore template?

If I feed underscore template with an object like

{
    key1: value1,
    key2: [value20, value21, ...]
}

then in template I can iterate over it using _.each(key2, function()).

But can I iterate through the array if it is top-level like

[
    val1,
    val2,
    ...
]

May be something like _.each(this, function())

Upvotes: 1

Views: 134

Answers (2)

killscreen
killscreen

Reputation: 1775

Yes. By default, the object passed into the template is named obj. lodash additionally allows this to be renamed using the variable property of the options argument passed in; I don't believe underscore supports this.

Demonstrating from the REPL:

> require('underscore').template('<%= obj.length %>')([ 'a', 'b', 'c' ]);
'3'
> require('underscore').template('<%= foo.length %>', { variable: 'foo' })([ 'a', 'b', 'c' ]);
ReferenceError: foo is not defined
> require('lodash').template('<%= foo.length %>', { variable: 'foo' })([ 'a', 'b', 'c' ]);
'3'

My source is the lodash docs; I skimmed through the underscore docs and didn't see a reference to this, so it may be unsupported functionality in underscore.

Upvotes: 0

Haseeb Asif
Haseeb Asif

Reputation: 1786

It seems you're looking for _.values.

var data = {
    key1: "value1",
    key2: ["value20","value21"]
};

console.log(_.values(data));
//["value1", ["value20", "value21"]]

Then you can do _.each on it to iterate through the list

Upvotes: 0

Related Questions