Iterating through each element of a JSON object using JavaScript

Here is a JSON data example:

{
    "email.com": ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8a828e8683af8a828e8683c18c8082">[email protected]</a>|username\r"],
    "email.de": ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73161e121a1a31a1612316">[email protected]</a>|username"]
}

My objective is to display it in the following format:

email.com
email.de

var data = '{"email.com":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9ccc4c8c0c5e9ccc4c8c0c587cac6c4">[email protected]</a>|username\r"],"email.de":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acc9c1cdc5c0ecc9c1cdc5c082c8c9">[email protected]</a>|username"]}';
var obj = JSON.parse(data);
for (i = 0; i < obj.length; i++) {
  document.getElementById('types').innerHTML += '<br>' + obj[i]; // I want to get email.com , email.de
}
<div id="types">
</div>

Answer №1

Everything is running smoothly:

var info = '{"website.com":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61040c00080d21040c00080d4f020e0c">[email protected]</a>|user123\\r"],"site.de":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2878f838b8ea2878f838b8ecc8687">[email protected]</a>|user321"]}';
var object = JSON.parse(info);
var identifiers = Object.keys(object);
for (i = 0; i < keys.length; i++) {
  document.getElementById('types').innerHTML += '<br>' + keys[i]; // Extracting website.com , site.de
}
<div id="types"></div>

Answer №2

let info = [{"website.com":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244139453d48364139453d480a474b49">[email protected]</a>|name\r"],"website.net":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60090d01090c20050d090c4e0405">[email protected]</a>|username"]}];
let key = (Object.keys(info[0])[0]);

let details = JSON.parse(info);
for (let j = 0; j < details.length; j++) {
  document.getElementById('types').innerHTML += '<br>' + details[j][key]; // Retrieving website.com , website.net
}

This code should do the trick

View solution for displaying object keys and values

Answer №3

Here is a straightforward approach that utilizes the String.match and Array.join methods:

var data = '{"email.com":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254048444c49654048444c490b464a48">[email protected]</a>|username\r"],"email.de":["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3b333f37321e3b333f3732703a3b">[email protected]</a>|username"]}',
    emails = data.match(/\w+\.\w+(?=\":\[)/g).join("<br>");
    
document.getElementById('types').innerHTML += '<br>' + emails;
// The 'emails' variable now holds "email.com<br>email.de"
<div id="types"></div>

Answer №4

hastily :

let data = {
    "email.com": ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72171f131b1e32171f131b1e5c111d1f">[email protected]</a>|username\r"],
    "email.de": ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57323a363e3b17323a363e3b793332">[email protected]</a>|username"]
};
for (let key in data)  console.log(key);

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

Is Webpack bundling the node_modules of node_modules into the bundle?

Recently, I noticed that webpack is bundling dependencies from the top-level node_modules directory into my actual bundle. For instance, one of my dependencies, example-dep, relies on lodash and has a nested node_modules directory at node_modules/example-d ...

Adding a new item to a list using Ajax after a post request - focusing on layout design

I currently have an activity stream available for users to use, as well as a site-wide view. When a user posts an update, it displays a default bootstrap success alert. However, I have noticed that other websites slide down existing items and append the ne ...

Prevent duplicate submissions by disabling the ASP.NET Forms button after it has been clicked

How can I disable an ASP.NET button after it's clicked to prevent double-clicking, and then enable it again after the submission is complete? I need some assistance with this. ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

"Using version 4.2.6 of NodeJS, create a constructor that takes a literal object as a

Currently, I am using NodeJS v4.2.6 which unfortunately has an issue with Block-Scoped declarations not being fully supported yet. Due to certain constraints, I am restricted to this version and have resorted to including the "use strict"; line to prevent ...

Utilizing a router to control a GET request for accessing an image file

Currently utilizing node.js in conjunction with the express framework, I am attempting to initiate a get request for an image by appending it to the body through $('body').append('<img src="images/image.gif?34567">'). Despite rece ...

Creating a multidimensional array without specifying index numbers

I have been pondering how it is possible to define char arrays in the following fashion: char szArray[]={"one"}; char szArrayTwo[][6]={{"one"},{"two"},{"three"}}; However, attempting to do so like this does not work: char szArrayTwo[][]={{"one"},{"two"} ...

Transform vertical and horizontal scrolling actions into solely horizontal scrolling using HTML and JS

I'm currently working on a unique React.js website that features a horizontal-scrolling portfolio. The website functions as a visual gallery, allowing users to easily scroll through images using their trackpad. Within the website, I have set up a lar ...

KnockoutJS - Using containerless control flow binding with predefined values

Inside a select control, I am using ko:foreach instead of the usual bindings. Everything is working perfectly, except that the initial value for "specialProperty" is set to unknown even when the select control is set to Option 1. It behaves as expected o ...

What is the best way to interact with DOM elements within PUG code?

I have a situation where I am working with an Express index page and there is a variable called 'data' that gets passed from express. My aim is to create a graph within the template by utilizing mdbootstrap with the data object supplied by expres ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Material Design - The element provided is not valid: it should be a string for built-in components or a class/function for composite components, but instead it is an object

How are you today? I am currently working on a React project using Webpack and Babel. I encountered an issue when trying to incorporate Material UI components from https://mui.com/. Whenever I import a MUI component into my project, I receive the followin ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

Having issues with Angular resolver not working as expected?

This demonstration showcases the issue: https://stackblitz.com/edit/angular-routing-with-resolver-observable?file=src%2Fapp%2Fpost-resolver.service.ts Replacing this.observeLoading$ with of(false) resolves the problem, indicating that it may be related t ...

What method can we use to temporarily route traffic from one URL to another URL for a specific amount of time?

Is there a way to use javascript/jquery code that will redirect my website to a different domain, but only during specific hours? I'm looking to have the redirection occur between 2 a.m. and 4 a.m., so that it only works for two hours out of the day. ...

Delay occurs unexpectedly when adding a class with jQuery to multiple elements

I am in the process of creating a flipping counter that is designed to change colors once it reaches a certain target number (in this case, 1000). However, I am noticing that the different sections of the counter do not change color simultaneously, there s ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

When two lists that were previously equal are now defined as unequal

ArrayList<Integer> list1= new ArrayList<>(); ArrayList<Integer> list2= new ArrayList<>(); for(int i=1;i<=5;i++){ list1.add(i); } System.out.println("List1 "+list1); list2=list1; System.out.println("List2 "+list2 ); list2.add(6); ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

How can you deduce the type from a different property in Typescript?

I have encountered obstacles in my development process and need assistance overcoming them. Currently, I am trying to configure TObject.props to only accept 'href' or 'download' if the condition TObject.name = 'a' is met, and ...