2015-08-01 14 views
8

Ho un semplice oggetto letterale che è l'indirizzo come qui mostratoejs come iterare oggetto

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

ed il suo interno un oggetto che sto passando con express.js funzione rendering.

nel mio modello di pagina che sto cercando di ciclo for all'interno di questo oggetto, come mostrato:

<% for (var prop in artist.address) { %> 
    <%- artist.address[prop] %> 
<% } %> 

che l'output dei dati, ma include le funzioni EJS così in questo modo:

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

così come ho bisogno di iterare il mio oggetto?

+0

buona risposta qui: http://stackoverflow.com/questions/14379274/javascript-iterate-object – snozza

+0

è 'indirizzo 'in realtà un' mongoose.Schema' e 'artist.address' è un' mongoose.Document'? – mscdex

+0

no, l'artista è un mongoose.schema var artistSchema = mangusta.Schema ({ indirizzo: { Paese: String, state: String, città: String, zip: String, strada: String }, .... –

risposta

4

utilizzando JS pianura è possibile utilizzare Object.keys

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

Nel tuo esempio

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

Un altro modo fresco è quello di utilizzare lodash: lodash forEach

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

Questo risponde come iterare in Javascript, la domanda del titolo OPs era come iterare in con EJS. Questa risposta è fuorviante per quelli portati qui alla ricerca di una risposta alla domanda nel titolo. – Cleanshooter

7

Stai visualizzando tutte le proprietà ereditate oltre alle proprietà "proprietarie" che hai aggiunto in cima.

Ci sono due modi per risolvere questo. Uno è quello di utilizzare hasOwnProperty() al fine di garantire che non si vede: le proprietà ereditate

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

o utilizzare Object.keys() che restituisce un array di solo le proprietà non-ereditate e iterare che:

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

Dal momento che questo è mangimi correlati, si può anche provare iterando su artist.address.toObject() (usando l'API pubblica) o artist.address._doc (usando un'API privata) o forse su un livello sull'oggetto artist.

+0

ancora facendo: <% Object.keys (artista .Address) .forEach (function (prop) {%> <% - artist.address [prop]%> <% }); %> sta tornando: function() {return this.get (percorso);} function() {return this.get (path);} yafo 09988 –

+0

Quali sono i nomi delle proprietà impreviste? – mscdex

2

OK così mi sono tuffato in esso ecco una spiegazione, avevo un oggetto:

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

avevo bisogno di visualizzare solo le proprietà e non ereditato una volta così ho iterare l'oggetto e ha ottenuto le sue proprietà:

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

ma il problema era che il mio oggetto artist.address ebbe altri due proprietà: ognuno tiene una funzione con un ritorno.

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

così ho controllato per le proprietà che contiene una stringa in questo modo:

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

è necessario capire quando si desidera utilizzare client ejs o server. se si utilizza sul lato server e permette di dire la sua esplicita: l'oggetto di ritorno dovrebbe essere simile a questo: controllore: ritorno res.render ('template/something.ejs', {_: require ('lodash '), artista: artistDocument}); vista template <% _ (artist.address) .forEach (function (prop) {%.><% - artist.address [prop]%><% }); %> lato client basta usare il servizio CDN per ottenere lodash