Tips for parsing a JSON object efficiently

Javascript

var obj = { 
    "name" : ["alex","bob","ajhoge"],
    "age" : [30,31,33]
};

To display the value "alex," you can use:

document.write(obj["name"][0])

But how can we filter through 'obj' to retrieve all data like this?

html

<ul>
  <li>name
     <ul>
       <li>alex</li>
       <li>bob</li>
       <li>ajhoge</li>
     </ul>
  </li>
  <li>age
     <ul>
       <li>30</li>
       <li>31</li>
       <li>33</li>
     </ul>
  </li>
</ul>

Thank you!

Answer №1

let x;
for (x in myObject) {
    if (myObject.hasOwnProperty(x)) {
        <li>x</ul>
        <ul>
        myObject[x].forEach(function (item) {
            return "<li>" + item + "</li>";
        });
        </ul>
    }
}

This code snippet demonstrates a way to iterate through an object and its elements. Please remember:

  1. Avoid using document.write for dynamic content.
  2. The inner loop structure is not actual code, but rather pseudo code.

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

What could be causing the image not to be centered inside the <table><td>?

Currently, I am developing a web application with Google Script that generates a dashboard featuring multiple tables. To design the layout, I am utilizing Bootstrap (https://cdn.jsdelivr.net/npm/[email protected] /dist/css/bootstrap.min.css). Despite ...

Issue with ERR_HTTP_HEADERS_SENT persists despite implementation of return statements

When attempting to send a POST request to the server, an error is encountered: Error [ERR_HTTP_HEADERS_SENT]: Cannot modify headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_h ...

Angularjs displays an error message stating, "Unable to assign value to property that is undefined"

Whenever I try to set a property, I encounter an error message stating "cannot set property of undefined". vm.dtr1 = {}; // Could it be that I have incorrectly initialized this? vm.dtr1.date1 = {}; // Could it be that I have incorrectly initialized this ...

Updating your Heroku app (Node.js) from a GitHub repository - a step-by-step guide

I attempted to deploy my React app using the following process: git status git remote add origin <repo link> git commit -m "node js" git add . Unfortunately, this method did not work for me. Can anyone provide guidance on how to update a ...

Guide to automatically filling in a form's fields with information from a database by clicking on a link

Currently, I have a form in HTML that is designed to gather user/member information. This form connects to a database with multiple columns, with two key ones being "user_email" and "invoice_id". Upon the page loading, the input for "user_email" remains hi ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

There is an issue with the JSON format being received by fetch in JS when using json_encode in php

Recently, I encountered an issue with my JavaScript function that retrieves data from a PHP page. In the JS code block: fetch("print.php) .then(function (r) { return r.json() }) .then(function (values) { ...... ...... ...

Customizable iterative functions for manipulating pandas dataframes?

I have developed a complex financial forecasting model that requires calculating projected spending for the year based on the previous year and then re-prioritizing the list accordingly. The main challenge is to calculate this for 30 years, with varying bu ...

Would it be unwise to create a link to a database directly from the client?

If I want to connect my React app to Snowflake all client-side, are there any potential issues? This web app is not public-facing and can only be accessed by being part of our VPN network. I came across this Stack Overflow discussion about making API cal ...

Encountering issues with returning values correctly when using module.exports in Node.js

function userLogin(username, password) { var status; var userid = username; User.findOne({ 'username': [userid], 'password': [password] }, function(err, user) { if (!user) { console.lo ...

Is there a way to utilize an AXIOS GET response from one component in a different component?

I'm having trouble getting my answer from App.tsx, as I keep getting an error saying data.map is not a function. Can anyone offer some assistance? App.tsx import React, {useState} from 'react'; import axios from "axios"; import {g ...

Buttons aligned vertically alongside an input text field

I am trying to align two buttons vertically under an input text box with the middle aligned. This is what I have done so far: jQuery(document).ready(function($) { // Implementing bootstrap minus and plus plugin // Reference: http://jsfiddle.net/lael ...

"execute loop in a strange and peculiar manner using JavaScript

Implement a loop to place markers on the map: for (i = 0; i <= 6; i++) { _coord = prj_markers[i]; alert(i); instance.set_marker(instance, provider, i, _coord, divBlock); } This code displays "0" in an alert once and executes instance.set_m ...

Controller experiencing peculiar AJAX response in CodeIgniter

I recently embarked on a Codeigniter project and now I'm faced with the task of making an AJAX call to a specific controller. Here is the scenario: - I have two dropdown menus: one for selecting counties and the other should populate with cities with ...

What is the best way to send information to a component using Props in Vue2?

Recently, I created a .Vue file to showcase information about a cafe on the Cafe Details Page. However, to streamline template updates, I decided to extract certain parts of this details page and turn it into its own component. This led me to create a new ...

Converting large numbers (exceeding 53 bits) into a string using JavaScript

I have a REST service that returns JSON. One of the properties in the JSON contains a very large integer, and I need to retrieve it as a string before Javascript messes it up. Is there a way to do this? I attempted to intercept every response using Angular ...

Node server encountering issue with undefined data in POST request

I have been working on an Angular2/Node.js application. Everything seems to be working fine when I retrieve an object from the Node server, but I'm facing an issue when trying to post data to the server. The request.body always shows as undefined. Can ...

What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with: [ { "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2" ...

Utilizing data as a substitute when creating a SearchBar using Vue3

My VueJs3 application has a search bar implemented using .filter(), and it seems to be working fine. However, when I try to pass the value from my methods to the template, an error occurs. My data becomes a proxy and I am unable to use it in that format. ...

Find the current elapsed time using Wavesurfer in real time

I am currently utilizing the waveSurfer library created by katspaugh for playing audio files. In order to display 'elapsed time / total time', I have written code in the following manner: waveSurfer.on('play', function() { $scope.g ...