ejs如何迭代对象
我有一个简单的对象文字是地址,如下所示
address: { country: String, state: String, city: String, zip: String, street: String }
它的内部是一个对象,我用express.js渲染函数。
在我的模板页面,我试图在这个对象内循环如下所示:
<% for (var prop in artist.address ) { %> <%- artist.address[prop] %> <% } %>
它输出的数据,但包括ejsfunction,如下所示:
function () { return this.get(path); } function () { return this.get(path); } yafo 09988 jerusalem israel israeli [object Object] undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined [object Object] [object Object] function () { var self = this , hookArgs // arguments eventually passed to the hook - are mutable , lastArg = arguments[arguments.length-1] , pres = this._pres[name] , posts = this._posts[name] , _total = pres.length , _current = -1 , _asyncsLeft = proto[name].numAsyncPres , _next = function () { if (arguments[0] instanceof Error) { return handleError(arguments[0]); } var _args = Array.prototype.slice.call(arguments) , currPre , preArgs; if (_args.length && !(arguments[0] == null && typeof lastArg ===
所以我如何需要迭代我的对象?
使用普通的JS你可以使用Object.keys
var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.keys(obj)); // console: ['0', '1', '2']
在你的例子中
var artist = { address: { city: 'Tel Aviv' } }; Object.keys(artist.address).forEach(function(key){ <%- artist.address[city] %> //key will city the output will be 'Tev Aviv' });
另一个很酷的方法是使用lodash: lodash for each
_([1, 2]).forEach(function(n) { console.log(n); }).value();
除了上面添加的“自己”属性外,您还可以看到所有inheritance的属性。
有两种方法可以解决这个问题。 一个是使用hasOwnProperty()
来确保你看不到inheritance的属性:
<% for (var prop in artist.address) { if (Object.prototype.hasOwnProperty.call(artist.address, prop)) { %> <%- artist.address[prop] %> <% } } %>
或者使用Object.keys()
,它返回一个只有非inheritance属性的数组,并迭代它:
<% Object.keys(artist.address).forEach(function(prop) { %> <%- artist.address[prop] %> <% }); %>
由于这是mongoose相关的,你也可以尝试迭代artist.address.toObject()
(使用公共API)或artist.address._doc
(使用私人API)或者artist
对象的一个级别。
好,所以我深入这里是一个解释,我有一个对象:
address : { country: String, state: String, city: String, zip: String, street: String }
我只需要显示那些属性,而不是一次inheritance,所以我遍历对象,并获得自己的属性:
<% Object.keys(artist.address).forEach(function(prop) { %> // ["country" , "state" , "city" etc ] <%- artist.address[prop] %> // so artist.address.state logs "New York City" <% }); %>
但问题是,我的artist.address
对象有两个更多的属性:每个拥有一个返回的函数。
function () { return this.get(path); } function () { return this.get(path); }
所以我检查了这样一个string的属性:
<% Object.keys(artist.address).forEach(function(prop) { if( typeof artist.address[prop] == "string" ) { %> <%- artist.address[prop] %> <% } %> <% }); %>