ejs如何迭代对象

ejs how to iterate object

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

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

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

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

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

那么我需要如何迭代我的对象?

除了您在顶部添加的 "own" 属性之外,您还会看到所有继承的属性。

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

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

或使用 Object.keys() 其中 returns 仅包含非继承属性的数组并对其进行迭代:

<% Object.keys(artist.address).forEach(function(prop) { %>
  <%- artist.address[prop] %>
<% }); %>

由于这是猫鼬相关的,您也可以尝试迭代 artist.address.toObject()(使用 public API)或 artist.address._doc(使用私有 API) 或者在 artist 对象上更上一层楼。

使用纯 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();

好的,所以我深入研究了这里的解释, 我有一个对象:

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

我只需要显示那些属性而不是继承一次,所以我遍历对象并获得了它自己的属性:

<% Object.keys(artist.address).forEach(function(prop) { %>
   // ["country" , "state" , "city" etc ]
  <%- artist.address[prop] %> // so artist.address.state logs "New York City"
<% }); %>

但问题是我的 artist.address 对象还有两个属性: 每个人都有一个 return.

的函数
function () { return this.get(path); } function () { return this.get(path); }

所以我检查了包含这样一个字符串的属性:

<% Object.keys(artist.address).forEach(function(prop) {
  if( typeof artist.address[prop] == "string" ) { %>
    <%- artist.address[prop] %>
  <% } %>
<% }); %>