ejs如何迭代对象 [英] ejs how to iterate object

查看:72
本文介绍了ejs如何迭代对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的对象常量,其地址如下所示

I have a simple object literal which is address as shown here

address: {
    country: String,
    state: String,
    city: String,
    zip: String,
    street: String
}

及其内部对象,该对象是我通过express.js渲染函数传递的对象。

and its inside an object which i'm passing with express.js render function.

在我的模板中页面我正在尝试在该对象内进行循环,如图所示:

in my template page i'm trying to for loop inside this object as shown:

<% for (var prop in artist.address ) { %>
  <%- artist.address[prop] %>
<% } %>

输出数据,但也包含ejs函数,如下所示:

which output the data but includes the ejs functions as well like so:

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 === 

那么我该如何迭代对象?

so how do i need to iterate my object?

推荐答案

使用纯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 forEach

Another cool way is to use lodash: lodash forEach

    _([1, 2]).forEach(function(n) {
  console.log(n);
}).value();

这篇关于ejs如何迭代对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆