Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved?

{
  data: {
    '1613152800': {
      i0: -264,
      i1: 297,
      i2: -260,
      i3: 270,
      i4: -159,
      i5: 0,
      i6: -7,
      i7: 145
    },
    '1613153400': {
      i0: 261,
      i1: -239,
      i2: 125,
      i3: -214,
      i4: -257,
      i5: 3,
      i6: -237,
      i7: -128
    }
  }
}

While this example showcases two primary entries ('1613152800' and '1613153400'), it is essential to note that there might be numerous such entries present.

Moreover, it's important to mention that I won't have prior knowledge of the main entry ids, meaning that '1613152800' and '1613153400' will always remain unidentified. Therefore, I cannot rely solely on

var json = JSON.parse(data);
console.log(json.data['1613152800'].i4);

as an approach.

Your insights would be greatly appreciated. Thank you!

Answer №1

If you want to extract specific values from an object, you can use a combination of Object.values and map:

const obj={ data: { '1613152800': { i0: -264, i1: 297, i2: -260, i3: 270, i4: -159, i5: 0, i6: -7, i7: 145 }, '1613153400': { i0: 261, i1: -239, i2: 125, i3: -214, i4: -257, i5: 3, i6: -237, i7: -128 } }}

const getEntries=(obj, key)=> Object.values(obj.data).map(({[key]:v})=>v);

console.log(getEntries(obj,'i4'));

Answer №2

If you want to iterate through the elements within your data object, you can accomplish that by following these steps:

var jsonData = JSON.parse(data);
var keys = [];
for(var key in jsonData.data) {
  keys.push(key);
}

Once you have an array of the keys, you can access the objects using their respective indices like this:

console.log(keys[0].i4);

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

Guide to utilizing various Nodelists using the forEach function

I'm currently developing an online store project that includes a shopping cart feature. My goal is to send a POST request to the server with the items selected by the user in the cart. I have initialized an empty array and I have 3 Nodelists containin ...

While typing, React-hook-form is removing the input field when the mode property is enabled

Currently, I am implementing a basic form using react-hook-form version 7 along with Material UI. However, I have encountered an unusual behavior when configuring the mode in useForm({mode: ".."}). Below is a snippet of my code: import { yupResol ...

Developing an npm module that is compatible with both web browsers and Node.js

Currently, I am in the process of developing an npm package that will cater to both web apps and other node modules. If my focus was solely on browsers, I would simply assign window.myExport = myExport; as a direct solution (unless there is a more contemp ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

What is the best way to alternate $httpBackend when[method] declarations in unit tests to handle multiple requests?

When conducting my testing, I set up the model data and mock the response: beforeEach(function(){ var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/); $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000}); }) ...

Struggling to Confirm Inaccuracies in Material UI Forms

Struggling to validate form errors in React with Material UI using JOI and running into issues. Even the console.log() results are not showing up in my validate function. The error display is also confusing. ... import React from "react"; import ...

Python JSON object iterated through using a for loop

Hi, I could use some help with parsing my JSON object. I'm trying to extract a specific JSON key and display its value. JSON Content { "files": { "resources": [ { "name": "filename", "hash": "0x001" }, { ...

NodeJS parseStream, setting boundaries for chunk extraction from a stream

Struggling with parsing Node's filesystem. Below is the code snippet in question: var fs = require('fs'), xml2js = require('xml2js'); var parser = new xml2js.Parser(); var stream = fs.createReadStream('xml/bigXML.xml&ap ...

Get the json output and replace any null values with an empty string

I'm dealing with an issue in my action that returns a JSON result. Some of the attributes come back as null, and I want them to be empty strings instead. Someone suggested using DefaultValue(""), but it's still giving me null values. This is the ...

Find the Time Difference in IST using JavaScript

Is there a way to calculate the time difference between two different time zones in javascript? var startTime = doc.data().startTime; output: Fri Dec 06 2019 19:00:00 GMT+0530 (India Standard Time) var currentTime = new Date(Date.now()).toString(); outpu ...

The callback function is not being executed in the Ajax request

$(document).ready(function(){ var requestURL = 'http://www.football-data.org/soccerseasons?callback=?'; $.ajax({ type: 'GET', dataType: 'json', url: requestURL, success: function(data){ cons ...

Tips for choosing the default tab on Bootstrap

I have a question about an issue I am facing with my Angular Bootstrap UI implementation. Here is the code snippet: <div class="container" ng-controller='sCtrl'> <tabset id='tabs'> <tab heading="Title1"> ...

Harvesting data from a simulated environment on the web

I'm currently facing a challenge while attempting to extract data from simulator websites. I am encountering difficulty in obtaining the JSON structure necessary for my task. Here is what I have attempted so far: import requests url_puzzle = ' ...

Learn how to extract data from the "this" object in JavaScript

Can anyone help me with retrieving the numbers generated by this code snippet? $("#100wattaren") .countdown("2018/01/01", function(event) { $(this).text( event.strftime('%D days %H hours %M minutes %S seconds') ); }); When I con ...

Error 500 occurred when attempting to access an external PHP file

I am currently utilizing WP Web Scraper version 3.2. When I place the shortcode or template tag (php code) directly into my page, the plugin functions correctly and displays the values. However, when I attempt to include the template tag in an external php ...

How to implement debouncing for an asynchronous custom validator in Vue.js using vuelidate?

I encountered an issue with my validator function that checks if a username is already registered in the database. The problem was that the request was being sent to the server after every single character input, which was far too frequent. To remedy this, ...

What could be causing the bootstrap 4 col-md-3 block to shrink when using position fixed?

When working with Bootstrap 4, I encountered an issue where changing the block position from relative to fixed using a script caused the block to decrease in size. The script I used includes a .sticky class: .sticky { position: fixed !important; top: ...

Tips for identifying a webpage and making class modifications based on it

I am working on a customized bar with 4 distinct parts. Each part corresponds to a different page on the website. I want each part of the bar to change color based on which page the user is currently browsing. For example, if the user is on page A, I want ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...