使用underscorejs获取javascript对象的键

时间:2013-10-27 20:35:57

标签: javascript backbone.js

如何使用underscorejs

获取javascript对象的键

我有一个看起来像这样的骨干模型对象

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

在我的模板中,我有以下

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

我得到以下预期输出

lunsize
type
age

虽然我的代码按预期工作,但我想知道有更好的方法来实现这个结果吗?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以使用:

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

如果您不确定是否有人使用了对象原型,那么使用.hasOwnProperty(prop)是件好事:

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

答案 2 :(得分:0)

你不需要Underscore.js。只需使用内置语言函数Object.keysArray.prototype.forEach

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

(我还将您从未转义的<%=切换为逃避<%-,以避免在您的密钥包含<>,{{1}等字符时出现问题},'"。)