Retrieve children of a specified node from a JSON object using JavaScript

I am in the process of developing a tool that can extract the Core Web Vitals metrics from a specified URL.

By utilizing the API, I am able to retrieve a JSON object which can be accessed with JSONPath.

I intend to utilize a forEach loop to populate the data into the HTML fields.

My current inquiry is regarding the method to access child nodes within a JSON structure without explicitly using their names.

document.querySelectorAll('[data-section^="cww"]').forEach((nodes, index) => {
    console.log(values.body.record.metrics);
});
{
    "key": {
        "origin": "https://developer.mozilla.org"
    },
    "metrics": {
        "cumulative_layout_shift": {
            // Histogram and percentiles data...
        },
        "first_contentful_paint": {
            // Histogram and percentiles data...
        },
        "first_input_delay": {
            // Histogram and percentiles data...
        },
        "largest_contentful_paint": {
            // Histogram and percentiles data...
        }
    }
}

Answer №1

give this a shot

const finalResult = [];

Object.keys(data.metrics).forEach(key => {
  const obj = {};
  obj.metric = key;
  obj.p75 = data.metrics[key].percentiles.p75;
  finalResult.push(obj);
});

result

[{"metric":"cumulative_layout_shift","p75":"0.01"},
{"metric":"first_contentful_paint","p75":841},
{"metric":"first_input_delay","p75":5},
{"metric":"largest_contentful_paint","p75":1135}]

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

Choose a Range of DOM Elements

My challenge is to select a range of DOM elements, starting from element until element. This can be done in jQuery like this: (Source) $('#id').nextUntil('#id2').andSelf().add('#id2') I want to achieve the same using JavaScr ...

Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading]. This particular ...

Adding options to a dropdown menu using jQuery and Ajax technique

After retrieving data from an Ajax call and attempting to append option values to a dropdown generated in jQuery, it doesn't seem to be working as expected. Here is the code snippet: $(document).on('focusout', '.generate', functio ...

What is the best way to incorporate a for loop in order to create animations with anime.js?

I am currently working on implementing a for loop to create a page loader using JQuery along with the animation framework anime.js var testimonialElements = $(".loader-animation"); for(var i=0; i < Elements.length; i++){ var element = ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

When an object is created, what is the most effective way to manage the asynchronous setup of one of its properties?

This is my first attempt at creating a JavaScript module/library, so I'm feeling a bit out of my depth. I apologize for not knowing exactly what to search for. My goal is to develop a library that stores information from a user-provided URL. The func ...

The values are not being displayed in the local storage checkbox

I attempted to transfer checkbox values to another HTML page using local storage, however they were not appearing on the other page Here is my page1 HTML code snippet: <input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW"> ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

Exploring the utilization of properties within the composition API

Can props be shared between components using the composition API, or is it still necessary to use mixins for that purpose? For instance, if I have a "visible" prop that I want to reuse in 5 components, how can I define it once and reuse it efficiently wit ...

Updating Bootstrap Indicators with jQuery on Click Event

Unfortunately, I am unable to share an image due to limited internet data. My goal is to switch each image to its sprite equivalent. There are three list items that I'm struggling to change because they each have two classes that need to be updated. ...

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Incorporating a for loop, ExpressJS and Mongoose repeatedly utilize the create method to generate

When users input tags separated by commas on my website, ExpressJS is supposed to search for those tags and create objects if they don't already exist. Currently, I am using a for loop to iterate through an array of tags, but only one object is being ...

What is the method for retrieving Polymer data that has been bound and incorporating it into a script?

My current setup involves utilizing the <firebase-document> element to retrieve data from Firebase. The data is then bound to {{poster}}, which allows me to access details of the poster object using its keys. For instance, {{poster.name}} displays th ...

Ways to flatten a structured json object

Looking to flatten a nested input JSON containing product attributes and items with their own attributes. The goal is to bring all the information to the root level, but struggling with the nested arrays. Unsure if it needs to be done in multiple steps. H ...

AJAX call error: Invocation not permitted

I'm currently working on a web application using JQuery that requires communication with a server. I've reused this code multiple times, only changing the data and success function. However, every time I execute this function, I encounter an err ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Is there a Python library that is comparable to simplejson/json but for XML?

Can anyone suggest an alternative library to simplejson that allows for fast data serialization to and from XML? For example: json.loads('{vol:'III', title:'Magical Unicorn'}') Or use json.dumps([1,2,3,4,5]) Open to any sug ...

Troubleshooting: Issues with MongoDB Aggregation not reflecting updates in my collection

Currently, I am attempting to execute an aggregation query in Mongo utilizing their nodejs driver. The query involves aggregating some fields, calculating averages, and other operations. I constructed the aggregation in Mongo Cloud and then exported it to ...