我有一个简单的对象字面量,就是这里显示的地址
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/