ejs how to iterate object

泄露秘密 提交于 2019-12-03 06:26:09

using plain JS you can use Object.keys

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

In your example

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' 
});

Another cool way is to use lodash: lodash forEach

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

You're seeing all of the inherited properties in addition to the "own" properties you've added on top.

There's two ways to solve this. One is to use hasOwnProperty() to ensure you don't see inherited properties:

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

Or use Object.keys() which returns an array of only non-inherited properties and iterate over that:

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

Since this is mongoose related, you may also try iterating over artist.address.toObject() (using the public API) or artist.address._doc (using a private API) or perhaps up a level on the artist object.

OK so i dived into it here is an explanation, i had an object:

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

i needed to display only those properties and not inherited once so i iterate over the object and got its own properties:

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

but the problem was that my artist.address object had two more properties: each one holds a function with a return.

function () { return this.get(path); } function () { return this.get(path); }

so i checked for properties that holds a string like so:

<% Object.keys(artist.address).forEach(function(prop) {
  if( typeof artist.address[prop] == "string" ) { %>
    <%- artist.address[prop] %>
  <% } %>
<% }); %> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!