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

What is the mechanism behind declaring a function using square brackets in Node.js/Javascript?

Encountering something new while working with Node.js - a unique way of declaring functions. You can find an example at this link. 'use strict'; const Actions = { ONE: 'one', TWO: 'two', THREE: 'three' }; clas ...

Is there a way to maintain the selected position on the drop-down menu for users?

Whenever I choose an option from the drop-down field in my form, it automatically jumps back to the top of the page. Just to clarify, I have a drop-down menu at the top of the page and several input fields below. Users need to scroll down to reach the dro ...

Accessing a subcollection with DocumentSnapshot in Firebase using JS9

Just had a quick question. Is anyone familiar with how to achieve something similar using Firebase JavaScript v9? Essentially, I have a `userDoc` that is a DocumentSnapshot and I need to access a sub-collection with the document snapshot. Here's the c ...

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

Animate the transition effect as soon as the block is displayed

Looking to create a smooth page transition using CSS changes with the help of Javascript (jQuery). Initially, one of the pages is set to display none. page1 = $('.page1'); page2 = $('.page2'); page1.removeClass('animate').cs ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...

Tips for importing a different js file from an npm package without needing to include the entire node_modules path

When using the ES2016 import syntax to load the select2 library from an npm module via Webpack, everything works smoothly and the select2.js file is loaded from the node_modules directory. The node_modules directory also contains a full version of the lib ...

several different objects within the rightIconButton of a ListItem component in MaterialUI

I am currently working on a project where I need to add multiple elements to the rightIconButton of a ListItem. The tools I am using are Material UI v0.20 and [email protected] <ListItem rightIconButton={ <span> ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Encountering a problem with ng-repeat when working with a JSON

Having a bit of trouble displaying the keys and values from a JSON object in an HTML table using ng-repeat. The JSON object is coming from the backend, but for some reason, it's not showing up on the frontend. I know there must be a simple mistake som ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Angular component.html does not compile due to a check that includes inline array creation

There is an enum called Status: export enum Status { SOME_VAL = "SOME_VAL", SOME_VAL_2 = "SOME_VAL_2", SOME_VAL_3 = "SOME_VAL_3"; } Also, I have an interface named SomeInterface: export SomeInterface { status? ...

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

Transform CI_Model into JSON format and then forward it to AJAX communication

How can I convert an object to JSON using json_encode and then send this JSON to AJAX as a response? Custom Code Example : <?php class CustomResponse extends CI_Model { private $status; private $data; public function __construct() { ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

The issue with .NET Core - SerializerSettings not taking effect

Configuration.cs services.AddMvc().AddJsonOptions(config => { config.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); DataConverter class JsonConvert.SerializeObject(dataObject) The SerializerSettings ...

Challenge with JSON Output Formatting in Azure Data Factory

I'm facing a problem with formatting the JSON output in Azure Data Factory. The structure I want for my JSON output is: { "AccessionNum": "12345", "test": [ { "orderunit": "JMJ", "Testname": "TVK" }, { "orderunit": "P ...

Exploring the implementation of query parameters in Nest.js

I am currently a freshman in the world of Nest.js. Below is an excerpt from my code: @Get('findByFilter/:params') async findByFilter(@Query() query): Promise<Article[]> { } I have utilized Postman to test this specific router. ht ...

Why is it that using e.preventDefault() does not prevent the link from being followed?

What is the solution to prevent a link from being followed with this specific event handler? http://jsfiddle.net/chovy/rsqH7/1/ <table> <tbody> <tr class="msg"> <header><a href="http://cn ...