node.js - ejs如何迭代对象

标签 node.js for-loop express ejs

我有一个简单的对象字面量,就是这里显示的地址

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

它在我通过 express.js 渲染函数传递的对象内部。

在我的模板页面中,我试图在这个对象内循环,如图所示:

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

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

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 forEach

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

关于node.js - ejs如何迭代对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31764552/

相关文章:

javascript - 所有脚本和页面加载完成后如何获取所有html数据? ( puppeteer 师)

css - LESS - 两个入门问题(编译选项和与 CSS 的组合)

javascript - Heroku - 特定路线在本地有效,但不适用于生产

javascript - 与 Webpack 的 resolve.root 选项同构 React

sql-server - SQL Server 连接到 Node js

c++ - 在 C++ 中,在 For 循环中使用非递增变量是否可以接受?

Python - 更快的循环方式

python - 计算 for 循环期间的运行总计 - Python

node.js - Mongoose:如何从express.js应用程序中的上限集合中获取数据?

javascript - 通过 NodeJS/Webix 在 MongoDB 中添加数据