Decoding json data with targeted API keys

Looking for some assistance here. I've got a JSON data set that looks like this:

[ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
]

What I'd like to do is transform it into the following format:

[2, 9, 6] and [4, 18, 12]

Answer №1

To achieve this, utilize the map function.

var data = [ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
];

const positiveList = data.map(({positive})=> positive);

const negativeList = data.map(({negative})=> negative);

console.log(positiveList);
console.log(negativeList);

Alternatively, you can consolidate it into a single map function.

   var data = [ 
     { "positive": 2, "negative": 4 }, 
     { "positive": 9, "negative": 18 }, 
     { "positive": 6, "negative": 12 } 
    ];

    const [positiveList, negativeList] = data.reduce(([a,b], {positive,negative})=>{ 
      a.push(positive); 
      b.push(negative); 
      return [a,b]; 
    }, [[],[]]);


    console.log(positiveList);
    console.log(negativeList);

Answer №2

Proven and reliable method

let data=[ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
];

let new_d=[]

data.map((e,i,a)=>{Object.keys(e).map((e1,i1,a1)=>{new_d[e1]=[...new_d[e1]||[],e[e1]]})})

console.log(new_d)

https://i.sstatic.net/hfSFG.png

Answer №3

If you want to achieve this, you can use a basic forEach loop. Here is an example:

const numbers = [ 
 { "positive": 2, "negative": 4 }, 
 { "positive": 9, "negative": 18 }, 
 { "positive": 6, "negative": 12 } 
]

const positiveNumbers = []
const negativeNumbers = []

numbers.forEach(number => {
  positiveNumbers.push(number.positive)
  negativeNumbers.push(number.negative)
})

console.log("Positive Numbers:", positiveNumbers)
console.log("Negative Numbers:", negativeNumbers)

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

Using Node.js to handle reading files and dealing with undefined or null values

The get method is responsible for receiving a userid with an initial total number of points defined in the stcok.json file, along with various transactions stored in another file. Below are some sample entries from the stock JSON: [ { "user" ...

What is the best way to choose the page number using numeric paging in RadGrid?

I have implemented a JavaScript function that binds onchange to onbeforeunload or a confirm box only when there are changes on the grid. My goal is to target the footer paging anchors in order to prevent triggering the confirm or onbeforeunload events. Us ...

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

unable to get highcharts to redraw and reflow properly

I am currently working on creating a dynamic page that can display between 1-4 graphs. These graphs need to be able to resize when added or removed from the page. However, I have encountered a major issue with resizing the graphs after resizing the contain ...

Alan AI does not support installation on React Native

❯ To install the @alan-ai/alan-sdk-react-native package, run: sudo npm i @alan-ai/alan-sdk-react-native --save > Post installation for @alan-ai/contact: > Copying AlanSDK.js, AlanButton.js, and AlanText.js to destination Mak ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Arranging the data in the table by alternating rows using Datatables

I need to organize my data in a way that includes an additional row for descriptive information, but this particular row should not be sorted. It is crucial for understanding the rest of the data, so hiding or showing it is not an option. Is it possible t ...

transform the stationary drawing to the top and left position at coordinate (0,0)

Exploring canvas has led me to encounter a puzzling issue with the translate method. While working on this fiddle http://jsfiddle.net/claireC/ZJdus/4/, my goal was to have the drawing move and bounce off all four walls. However, I noticed that it would no ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

Can you explain how the functionality of `v-b-modal` and `v-b-toggle` attributes operate and where they are monitored?

I'm trying to figure out how to add a custom attribute that triggers events, similar to the ones in this example. However, I can't seem to understand how they function. For instance: <b-button v-b-modal.modal-1>Launch demo modal</b-but ...

Using Vue.js and Django Rest Framework to prevent CSRF attacks in the POST method by implementing CSRF Tokens

Attempting to send a POST request from a Vue.js template to my Django API is resulting in a 403 error stating CSRF token missing or incorrect. Since I have separated the front and back end, I do not have a view with {csrf_token} on the Django side. How ca ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Increased wait time during initial execution

Currently facing an issue with delaying the first run of a function. I've developed a basic slideshow that is causing problems due to this delay in the initial run. My goal is to have the first run wait for 10 seconds and then maintain a 4-second del ...

Tips for utilizing the window object in Angular 7

To implement the scrollTo() function of the window object directly, we can use window.scrollTo(0,0). However, when researching how to do this in Angular, I found that many people create a provider as shown below: import {InjectionToken, FactoryProvider} f ...

What is the method to retrieve the value of a JSON object when the key matches the value of another JSON object?

Looking to expand my knowledge in javascript with an interesting challenge. Is there a way to retrieve the value of an object using another object's value as the key? For example: Obj1 = {"name":"John", "age":30, "car":null}; Obj2 = {"John":{"count ...

Using additional properties when referencing another Mongoose schema

var UserSchema = new Schema({ job : [{ type : mongoose.Schema.Types.ObjectId, experience : String, grade : String, ref: 'Company'}] }); User's profile can include multiple jobs. The process of adding a job to the user is a ...

Executing a mousedown event in Ajax while simultaneously running another JavaScript function using JQuery

One issue I am facing involves a JavaScript method. There is a date slider for months that triggers an AJAX call when the month is changed (mouseup event). Within this AJAX call, there is another JavaScript code ($.blockUI) which seems to interfere with th ...

Having an issue with the return function in a jQuery $.ajax call

I am currently working with a $.ajax call that is structured like this: <script type="text/javascript"> $(document).ready(function () { $('#add_com_frm').submit(function (e) { e.preventDefault(); var $b ...

Encountering a problem while trying to deactivate Navigation Buttons in VueJs

When working on my ticket processing application, I encountered a situation where I wanted to make the back and forward buttons in my TicketRunner.vue Component appear only if there was an associated case file. To achieve this, I utilized V-If as shown bel ...

Troubleshooting issue: Next.js Material-ui CSS SSR not functioning properly within components

Upon completing my project, I discovered that SSR for Material-ui is not functioning on the page where I utilized functional components. Here is my _document.js file: [Code from _document.js] Example Page: [Code from E ...