tawheed
tawheed

Reputation: 5821

get keys of javascript object using underscorejs

How do you get the keys of a javascript object using underscorejs

I have a backbone model object that looks like this

 {
   lunsize: "big",
   type: {mike: "who", james: "him"},
   age: 89
}

In my template I have the following

<% var b = _.keys(this.model.attributes) %> 
<% for (var i = 0; i < b.length; i++ ) { %>
<%= b[i] %>
<% } %>

I get the following expected output

lunsize
type
age

Although my code works as expected, am wondering is there a better way to achieve this result?

Upvotes: 1

Views: 330

Answers (3)

Domenic
Domenic

Reputation: 112857

You don't need Underscore.js for this. Just use the built-in language functions Object.keys and Array.prototype.forEach.

<% Object.keys(this.model.attributes).forEach(function (key) { %>
    <%- key %>
<% }); %>

(I have also switched you from unescaped <%= to escape <%-, to avoid problems if your keys ever contain characters like <, >, ', ", or &.)

Upvotes: 0

Jakub Roztocil
Jakub Roztocil

Reputation: 16242

<% _.each(this.model.attributes, function(value, name) { %>
    <%- name %>
<% }) %>

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47119

You can use:

for ( var prop in this.model.attributes ) {
    prop;
}

If you are not sure about if someone extented the Object prototype its a good thing to use .hasOwnProperty(prop):

for ( var prop in this.model.attributes ) {
    if ( this.model.attributes.hasOwnProperty(prop) ) {
        prop;
    }
}

Upvotes: 1

Related Questions