ejs如何迭代对象

Boa*_*och 13 for-loop ejs node.js express

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

address: {
    country: String,
    state: String,
    city: String,
    zip: String,
    street: String
}
Run Code Online (Sandbox Code Playgroud)

它的内部是一个我用express.js渲染函数传递的对象.

在我的模板页面中,我正在尝试在此对象内循环,如下所示:

<% for (var prop in artist.address ) { %>
  <%- artist.address[prop] %>
<% } %>
Run Code Online (Sandbox Code Playgroud)

它输出数据但包含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 === 
Run Code Online (Sandbox Code Playgroud)

那我怎么需要迭代我的对象?

msc*_*dex 9

除了您在顶部添加的"自有"属性之外,您还可以看到所有继承的属性.

有两种方法可以解决这个问题.一种是用来hasOwnProperty()确保你看不到继承的属性:

<% for (var prop in artist.address) {
     if (Object.prototype.hasOwnProperty.call(artist.address, prop)) { %>
       <%- artist.address[prop] %>
<%   }
   } %>
Run Code Online (Sandbox Code Playgroud)

或者使用Object.keys()返回只有非继承属性的数组并迭代它:

<% Object.keys(artist.address).forEach(function(prop) { %>
  <%- artist.address[prop] %>
<% }); %>
Run Code Online (Sandbox Code Playgroud)

由于这是与mongoose相关的,因此您也可以尝试迭代artist.address.toObject()(使用公共API)或artist.address._doc(使用私有API)或者在artist对象上升级.


Dor*_*gal 7

使用普通JS,您可以使用Object.keys

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
Run Code Online (Sandbox Code Playgroud)

在你的例子中

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' 
});
Run Code Online (Sandbox Code Playgroud)

另一个很酷的方法是使用lodash:lodash forEach

    _([1, 2]).forEach(function(n) {
  console.log(n);
}).value();
Run Code Online (Sandbox Code Playgroud)

  • 这回答了如何在Javascript中进行迭代,OPs标题问题是如何使用EJS进行迭代.对于那些在标题中寻找问题答案的人来说,这个答案是误导性的. (12认同)