1

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?

4

3 回答 3

2
<% _.each(this.model.attributes, function(value, name) { %>
    <%- name %>
<% }) %>
于 2013-10-27T20:44:34.647 回答
1

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;
    }
}
于 2013-10-27T20:38:18.440 回答
0

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 &.)

于 2013-10-27T20:38:13.463 回答