AnonUser AnonUser - 5 months ago 28
JSON Question

How to retrieve an object inside an object in EJS

I am trying to retrieve the "info" section of the JSON below. As you can see in my code I use the

<%= person['person_details']%>


to retrieve that section of JSON. This returns [Object Object]. What I want to do is retrieve everything in the info section of JSON a.k.a: "jim" "bob" "true" and "Two guys walk into a bar, one says: ow!". Some of the JSON doesn't have the same fields (I added another example below). I've tried doing...

<%= person['person_details'][0][1]%>


But this gives back an error. If I remove the [1] it gives back an empty quantity in my drop down menu.

<div class="personForm">
<form>
Select Parameters
<select id="personIdList">
<% data1.forEach(function(person) {%>
<option><%= person['person_details']%>
<% }); %></option>
</select>
</form>
</div>


//JSON THAT IM ATTEMPTING TO EXTRACT
"person_details": {
"info": {
"name": "Jim",
"lastName": "Bob",
"isMale": true,
"favJoke": "Two guys walk into a bar, one says: ow!"
}
},
//EXAMPLE 2
"person_details": {
"info": {
"email": "bobsmit@gmail.com",
"lastName": "tim",
"isMale": true,
"momMaidenName": "felicia"
}
},
//EXAMPLE 3 (info changes to information)
"person_details": {
"information": {
"email": "bobsmit@gmail.com",
"lastName": "tim",
"isMale": true,
"momMaidenName": "felicia"
}
},

Answer

You need to loop through the keys of each person's respective person_details. From there you'll use the keys ass accessors to the values.

For example:

<% data1.forEach(function(person) {%>
   <option>
     <% Object.keys(person.person_details.info).forEach(function(key) { %>
       <%= person.person_details.info[key] %>
     <% }); %>
  </option>
<% }); %>

This is a dynamic approach and will work with any set of key/values you have in your info hash.

If your person_details information hashes contain different names, you can monkey patch that in the loop (although I would recommend you normalize your data instead and use the first example).

<% data1.forEach(function(person) {%>
   <% var infoKey = infoKey = Object.keys(data1.person_details)[0]; %>
   <option>
     <% Object.keys(person.person_details[infoKey]).forEach(function(key) { %>
       <%= person.person_details[infoKey][key] %>
     <% }); %>
  </option>
<% }); %>

In this example, you dynamically find the name of the info key and set it to an infoKey var. From there you use that as the accessor.