Guide on accessing nested objects in EJS templates

I'm attempting to extract the "info" portion from the JSON data provided below. In my code snippet, I'm using the

<%= person['person_details']%>

to access that specific section of the JSON. However, it only returns [Object Object]. What I really want is to retrieve all the details in the info section of the JSON like: "Jim", "Bob", true, and "Two guys walk into a bar, one says: ow!". The challenge arises when some JSON objects have different fields (another example is added below). I've tried...

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

But this throws an error. Removing the [1] results in an empty dropdown menu selection.

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


//JSON DATA TO BE EXTRACTED
"person_details": {
    "info": {
        "name": "Jim",
        "lastName": "Bob",
        "isMale": true,
        "favJoke": "Two guys walk into a bar, one says: ow!"
    }
},
//ANOTHER EXAMPLE
"person_details": {
    "info": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0904091806021f2b0c060a020745080406">[email protected]</a>",
        "lastName": "tim",
        "isMale": true,
        "momMaidenName": "felicia"
    }
},
//YET ANOTHER EXAMPLE (with 'information' instead of 'info')
"person_details": {
    "information": {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096b666b7a64607d496e64686065276a6664">[email protected]</a>",
        "lastName": "tim",
        "isMale": true,
        "momMaidenName": "felicia"
    }
},

Answer №1

To iterate through the keys of each individual's corresponding person_information, you will need to use the keys as accessors to retrieve the values.

Here is an example:

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

This approach is dynamic and can handle any key/value pairs within your info object.

If the names in your person_details information objects are different, you can address this within the loop by dynamically identifying the correct key (although it is recommended to standardize your data structure and go with the first example).

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

In this scenario, you dynamically determine the name of the info key and store it in the variable infoKey. You then utilize this variable as the accessor for retrieving the values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that the submit button triggers the display of results with each click

My project involves two navigation bars, each with its own table displayed upon page load. Additionally, there is a search bar used to display search results in another table. The issue I'm encountering is that when I click the submit button once, th ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...

Tips for Elevating State with React Router Version 6

Looking for advice on sharing state between two routes in my project. I'm debating whether to lift state up from my AddContact component to either the Layout or App components in order to share it with the ContactList. The Layout component simply disp ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...

Creating collections in a Hashtable style using JavaScript

Creating a collection in JavaScript can be done in the following way: Start by initializing an empty collection with var c = {}; Next, you can add items to it. After addition, it will look like: { 'buttonSubmit': function() { /* do some work * ...

Transferring JavaScript files via Node server using NowJS

As someone new to Node, I need some help with a server-client web application I'm creating for a board game using Raphael for graphics. The issue I'm facing is that while the server successfully sends the HTML file in response to requests, the b ...

A step-by-step guide on integrating associations from json files using sequelize-fixtures

Greetings everyone, I am new to sequelizejs and currently exploring its functionality. I am encountering difficulties in creating example datasets using sequelize-fixtures. This is how my models are set up: User.js (without beforeCreate, beforeUpdate ho ...

Is there a way to replicate Twitter's "what's happening" box on our website?

Currently, I am trying to extract the cursor position from a content-editable box. However, when a new tag is created, the cursor appears before the tag instead of after it. Additionally, I am having trouble with merging/splitting the tags. Any suggestions ...

Editing input within a Bootstrap 4 popover causes it to lose focus

I am using Bootstrap 4 along with the Bootstrap colorpicker to implement a colorpicker within a popup that includes an input field for setting the color code. However, I am facing an issue where the input field (#color-value) seems uneditable when the popo ...

Exploring the Potential of jQuery through iBooks

Would like to know how to fix an issue with an interactive glossary I'm creating for an iBooks eBook. When clicking on a term, the definition should appear at the end of the page. Hiding the definition can be done by clicking on the term again or by c ...

Deleting empty tags in an HTML h1 element with JavaScript

Is there a way to use JavaScript to remove empty h1 tags only? <h1>Hello World!</h1> <p>Lorem ipsum dolor sit amet</p> <h1></h1> <p>consectetur adipiscing elit.</p> <h1></h1> <p>Sed do ...

Having trouble utilizing NPM package within AWS Lambda environment, encountered issue with require() function

Recently, I developed a simple NPM package consisting of just two files. Here is the content of index.js: module.exports = { errors: { HttpError: require('./src/errors').HttpError, test: 'value' } } And here& ...

What is the best way to merge two foursquare requests into one?

I'm a newcomer here trying to work with the FourSquare API. I'm not entirely confident in my approach, but I am attempting to retrieve data from a search using "". However, I also want to gather more details about each venue, such as their hours ...

Exploring Neo4j's Data Organization: Matrix versus Json for Handling Large Datasets

We are currently in the process of calculating term frequency (tf-idf) for various documents. Each term is being represented as a node, connected to multiple documents. Our task involves populating our Neo4j database with weighted relationships between te ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

Discovering the data types of various dictionary values within a JSON file can become a bit tricky when dealing with null values

I am working with a large set of dictionaries from a JSON file, each containing the same keys but different values that can be of multiple types, including null. I need to determine the type of each value so that I can initialize the appropriate variables ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

Troubleshooting: AngularJS not displaying $scope variables

I have a question that has already been answered, but the suggested solutions did not work for me. Everything seems to be fine, but the content within curly brackets is not displaying on screen. <div ng-controller="Hello"> <p>The I ...