I have a simple object literal which is address as shown here
address: {
country: String,
state: String,
city: String,
zip: String,
street: String
}
and its inside an object which i'm passing with express.js render function.
in my template page i'm trying to for loop inside this object as shown:
<% for (var prop in artist.address ) { %>
<%- artist.address[prop] %>
<% } %>
which output the data but includes the ejs functions as well like so:
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 ===
so how do i need to iterate my object?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With