Adding the children of JSON objects to every individual div element

How can I add each day's players [day-1, day-2, day-3, day-3] wrapped in a <span> into the .card-body section as required? The goal is to load only four card-body.

var vehicles = {
  "day-1": {
    "player-1-1": "Ford",
    "player-1-2": "BMW"
  },
  "day-2": {
    "player-2-1": "Benz",
    "player-2-2": "KIA",
  },
  "day-3": {
    "player-3-1": "Toyota",
    "player-3-2": "Mazda",
  },
  "day-4": {
    "player-4-1": "Honda",
    "player-4-2": "Nissan",
  },
}

Object.getOwnPropertyNames(vehicles).forEach((val, index) => {
  var txt = Object.values(vehicles[val]);
  console.log(txt);
})
span {
  background: orange;
  color: #fff;
  display: inline-block;
  float: left;
  padding: 12px;
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>

Answer №1

To easily add the HTML code to the body of the document, you can simply append it like this:

var cars = {
  "day-1": {
    "player-1-1": "Ford",
    "chapter-1-2": "BMW"
  },
  "day-2": {
    "player-2-1": "Benz",
    "player-2-2": "KIA",
  },
  "day-3": {
    "player-3-1": "Toyota",
    "player-3-2": "Mazda",
  },
  "day-4": {
    "player-4-1": "Honda",
    "player-4-2": "Nissan",
  },
}

Object.getOwnPropertyNames(cars).forEach((val, index) => {
  var txt = Object.values(cars[val]);
  document.body.innerHTML += `<div class="card-body">${txt}</div>`;
});
span {
  background: orange;
  color: #fff;
  display: inline-block;
  float: left;
  padding: 12px;
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you prefer to use the keys such as day-1, day-2, etc. instead of the car names, simply swap out the txt variable with val in the second-last line.

document.body.innerHTML += `<div class="card-body">${val}</div>`; 

Answer №2

To dynamically add the

<div class="card-body"></div>
using Javascript/jQuery only when necessary, follow this example: In your HTML, insert a div with an id:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

Next, in your Javascript:

var tds = new Array();
var j = 0;
Object.getOwnPropertyNames(cars).forEach((val, index) => {
  var txt = Object.values(cars[val]);
  tds[++j] = "<div class='card-body'>";
  tds[++j] = "<p>"+ txt.split(',')[0] +"</p>"
  tds[++j] = "<p>"+ txt.split(',')[1] +"</p>"
  tds[++j] = "</div>";
});
$("#result").append(tds.join(''));

That's it! Your task is now complete.

I included the code shared by jack-bashford to access the JSON Object without testing it. In case of any issues, you will need to troubleshoot and resolve them accordingly.

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

Chrome's Surprising Cross-Domain File URL Problem

Is anyone else experiencing the issue with Chrome throwing a Cross Domain Error when using file URLs? I'm trying to embed an SVG document into an HTML page using the object tag with a relative path in the data attribute. Upon the onload event, I need ...

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

Remove a specific date entry from the database using VUE JS and Axios

I am encountering a challenge with Vuejs as I work on a To-Do list. The tasks need to be stored in a MySQL database, and I also want the ability to delete tasks. While I have succeeded in importing and creating data, I'm facing difficulty in deleting ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Using the async.waterfall function in an Express application

Query: I'm encountering an issue with my express.js code where, upon running in Node.js, an empty array (ganttresult) is initially displayed. Only after refreshing the browser do I obtain the desired result. To address this problem, I have attempted ...

Where can I locate HTML codes within WordPress?

Upon inspecting the page source, I came across the following code snippet; https://i.sstatic.net/R7Fw3.jpg I attempted to search within WordPress for the HTML codes that are displayed here, but unfortunately, I was unable to locate them. I couldn't ...

Accessing dynamically created AJAX controls in ASP.NET during postback operations

I am dynamically creating 2 dropdown boxes and a CheckBoxList control using AJAX callbacks to a web service (.asmx file). The server-side service generates the Dropdowns and CheckBoxList, returning the rendered html as a string which is then inserted into ...

Click the button in Javascript to add new content

I am currently experimenting with JavaScript to dynamically add new content upon clicking a button. Although I have successfully implemented the JavaScript code to work when the button is clicked once, I would like it to produce a new 'hello world&ap ...

creating a multi-tiered dropdown menu using both CSS and JavaScript

I am in need of a multi-level (drop down) menu feature, that allows me to make changes to the menu in just one file, without having to navigate through each individual page. I require a three level menu. I have attempted to modify someone else's code ...

Issue with mobile browser validation for text field functionality not functioning properly

Issue with text box validation on mobile browsers for my Angular application Mobile Browsers: Chrome, Samsung Browser (not working in both) Expected Input: Numbers 0-9 and Alphabets A-Z only in the text field My Approach : 1. Initial Attempt: I attempted ...

How can the cross-domain AJAX form submission be achieved?

I am currently utilizing jQuery along with the jQuery form plugin Within the jQuery form plugin, there is a method called ajaxSubmit. This method allows you to submit a form via ajax and receive a response. I find it intriguing how this process works even ...

What is the best way to search for a specific item in Express.js?

I recently got the Leaderboard API issue fixed, but now I'm encountering a new problem with express Querying. Specifically, I'm attempting to search for a specific Discord ID using quick.db as my database. I've included an excerpt of my expr ...

React Issue: Make sure to assign a unique "key" prop to each child element within a mapped list

I encountered the error message below: react Each child in a list should have a unique "key" prop. Here is my parent component code snippet: {data.products .slice(4, 9) .map( ({ onSale, ...

Using jQuery, you can easily pass an array in an AJAX request

I am working on a form that has multiple identical fields: <input type="text" id="qte" value="" name="qte[]"> How can I pass the array to my file processing? I have observed that the array sent via ajax is converted into a string. $("#form_comman ...

Deleting the clone <div> while ensuring the main <div> is kept clear of any remaining data

Initially: https://i.sstatic.net/SLG7O.png After adding a new row and then removing it. https://i.sstatic.net/FegjK.png Why is this happening? When I set val(""), the textbox should have no value. What mistake did I make in my code? Please assist. Her ...

Creating an array based on specific conditions being satisfied (Using Javascript)

I am struggling with a coding problem involving adding users to groups. The goal is to add each user to a group array, with a maximum of 3 users per group. If a group reaches 3 users, it should be moved to another array that collects all the groups. I then ...

Unlock the potential of Bootstrap 4 in Vue.js 2 without the need for bootstrap-vue

I'm interested in finding a way to incorporate bootstrap 4 into my vue.js 2.6 framework. Despite the abundance of tutorials available, many of them are outdated as of late 2020, or they insist on using bootstrap-vue, which introduces unwanted addition ...

Checking for correct format of date in DD/MM/YYYY using javascript

My JavaScript code is not validating the date properly in my XHTML form. It keeps flagging every date as invalid. Can someone help me figure out what I'm missing? Any assistance would be greatly appreciated. Thank you! function validateForm(form) { ...

Show a notification on the screen if the source of the iframe is blank

Is there a way to show a message "Please click on a match to get started" when no match link has been clicked? For example, when the iframe does not have an src attribute. My backend is built on Django. Below is the HTML code snippet: </form><b ...