Divide a single JSON response into multiple individual objects

After spending a few hours on this, I've hit a roadblock. My app is returning a single JSON object with 4 datasets that I need to parse and use to create 3 charts and a table. However, I'm struggling to extract each part from the JSON structure which looks like:

{
   "allele":{
      "12426597":{
         "??":4,
         "CC":3,
         "TT":4,
         "CT":12
      },
      "878198":{
         "??":4,
         "AA":1,
         "AC":15,
         "CC":3
      },
      "6447271":{
         "??":4,
         "GG":14,
         "AG":5
      }
   },
   "haplo":{
      "CT,AG,AC":3,
      "TT,GG,AC":1,
      "CC,GG,CC":1,
      "TT,AG,CC":1,
      "TT,GG,CC":1
   },
   "exercise":"p1"
}

My goal is to extract data for the three specific keys/IDs (12426597, 878198, 6447271) and create a bar chart for each of them using Highcharts. This requires some data transformation as well as formatting the keys and values into ordered arrays as per Highcharts API requirements.

I initially tried creating an array of the IDs like this:

var snpsObj = data.allele_frequency; // data returned from $.getJSON
var snpList = [];

for (prop in snpsObj) {
    if (!snpsObj.hasOwnProperty(prop)) {
        continue;
    }
    snpList.push(prop);
}

This gives me the desired array. Then I attempted to access the sub-keys using:

snpsObj.snpList[0];

Hoping it would return something similar to:

{
   "CC" : 23,
   "CT" : 36,
   "TT" : 12,
}

Unfortunately, this approach did not work as expected. The closest I got was a return result of:

allele_frequency : [object Object ]

I know there must be a simple solution that I'm overlooking due to my current head cold-induced mental fog. Any suggestions on how to proceed?

Remember, Highcharts needs the keys and labels to be formatted in arrays such as:

categories: ['C', 'T'] data: [ 3, 9] // C=3, T=9

Answer №1

To access the desired information, you can utilize:

snpsObj[ snpList[0] ]

It is important to use bracket notation for this purpose. Trying to access it with snpsObj.snpList[0] would target the "snpList" property within your snpsObj object.

Instead of using a for-in-loop to generate an array with property names, consider utilizing Object.keys (even if you need to provide support for older browsers).

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

Encountering unhandled promise rejection error with email field in NextJS when using React Hook Form

I am encountering a bizarre issue where, on my form with two fields (name and email), whenever the email field is focused and onSubmit is called, I receive the following error message: content.js:1 Uncaught (in promise) Error: Something went wrong. Please ...

My API encountered a 404 error when trying to access the MAILCHIMP API

I am currently working on a project focused on creating a Newsletter for web development led by Angela Yu. In this project, I encountered a 404 error while integrating the API from the MAILCHIMP website. Each time I tried to insert the API, it consistent ...

Ensure that the jQuery Ajax each function verifies if the returned ID matches the one preceding it

Using AJAX, I am fetching data from a remote server and then using a loop to iterate through it. My goal is to perform an action only once if the returned value data matches the previous one. For example, if there are 10 instances of val.userId == 1, I wa ...

Guide to adding a personalized HTTP header to ajax request using JavaScript or jQuery

Is there a way to create a custom HTTP header using JavaScript or jQuery? I've tried the code below but it's giving me an error of 405 Method not Allowed. I'm using the POST method, but in the request it shows as OPTION. The status code is ...

A guide on finding identical objects in two separate arrays using JavaScript

Is there a way to achieve the following? const array1 = [{data1}, {data2},{data3}] const array2 = [{data1}, {data4},{data5}] The desired output is: {data1} ...

Combining Multiple Rows into a Single Record with Multiple Columns in PHP

Okay, so I have a bit of a tricky situation here that I need help with. Let me break it down for you. The challenge I'm facing is this: I have a MySQL table with around 600,000 rows and I need to export these records into a CSV file. The issue is tha ...

Ways to store the data obtained from a componentDidUpdate() method for future use in displaying purposes

export default class newroom extends Component { constructor(props) { super(props) this.state = { currentUser:NaN, rooms:NaN } } static getDerivedStateFromProps(nextProps, prevState){ // console.log(prevState) con ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

In JavaScript, when parsing JSON, the data seems to always be undefined

I'm currently attempting to parse a JSON file from an online source. Feel free to check out the link yourself. Unfortunately, no matter what I try, I keep getting 'undefined' when trying to access the data. All I want is some kind of output ...

What is the best way to extract data from a JSON response in iOS after making an HTTP POST request

After sending parameters to my server using the POST method, I receive a response and store it in a variable called "serverResponse". Here is an example of the JSON data contained within the server response: { "carIdentifier":[ {"carId":"91"} ...

How can I check if the VPN is turned off in a React application?

import React from "react"; import { Offline, Online } from "react-detect-offline"; export default function DropDown() { return ( <> <Online>Only displayed when connected to the internet</Online> <Offline ...

Having trouble navigating through filtering in JavaScript using Node and Express?

After experimenting with different methods, I noticed that when using (age => age.Book === book && age.Chapter === 1) as my filter criteria, everything works perfectly. However, when I try using (age => age.Book === book && age.Chapt ...

Exploring various parameters in React JS

Recently, I've been delving into a project using React js, which I initially thought would be similar to React native. Having prior experience with React native, most of React js is familiar to me. However, there are still new concepts I am learning, ...

Accessing instance variables from javascript can be made possible using the

I am currently facing an issue in my Rails app where I need scripts to have different behaviors based on the controller and action they originate from. To address this, I have set up the following code in my ApplicationController: before_filter :save_acti ...

Scrolling is endless with jCarousel - just press a button to keep moving even when you reach the first or

I seem to be experiencing a problem with jCarousel where, upon starting at the beginning, pressing the left button fails to scroll the carousel. The expected behavior is for the carousel to cycle to the end item when the left button is pressed while the f ...

Implement 2 new search options into the datatable plugin

Looking to enhance my existing panel by adding 2 search options: Here are the credentials you'll need: username: admin pass: Nopass1234 The additional features I want to include are: 2 search options: 1. from date 2. to date What will happen w ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

Unable to upload file in angular2 due to empty Body (FormData)

Attempting to upload a photo with Angular2 to my REST Service (Loopback). The Loopback service has been successfully tested using Postman and is able to accept files with the x-www-form-urlencoded header. Below is a simplified version of the service metho ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

Highchart: precise positioning of ticks on axis

Is there a way to precisely determine the distance or establish an exact distance (in pixels) between two ticks on the x-axis using Highchart? I attempted to use tickPixelInterval, but it doesn't appear to accurately set the distance between two tick ...