Sanjai Kumar
Sanjai Kumar

Reputation: 67

How to change the json structure

I'm developing React in my applications. is that any possible to convert the data as per the expected.

the data which i got from the backend is given below

[
{close: 37382,
date: "2021-01-22",
f_date: Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time) ,
high: 39251,
low: 10555,
open: 11111},
{close: 37382,
date: "2021-01-22",
f_date: Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time), 
high: 39251,
low: 10555,
open: 11111},
{close: 37382,
date: "2021-01-22",
f_date: Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time),
high: 39251,
low: 10555,
open: 11111}
]

need the format above data as by the following expected data [{x : f_date,y:[open,high,low,close]}..]

expected format

[
 {x : Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time),y :[11111,39251,10555, 37382]},
 {x : Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time),y :[11111,39251,10555, 37382]},
 {x : Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time),y :[11111,39251,10555, 37382]},
 {x : Fri Jan 22 2021 00:00:00 GMT+0530 (India Standard Time),y :[11111,39251,10555, 37382]},
]

how to convert the json data by expected format.?

Upvotes: 0

Views: 50

Answers (2)

sarfrazanwar
sarfrazanwar

Reputation: 393

From what I could understand you can just iterate over the input data and create a new list in the expected format like this :

 expectedData = []     
    inputData.forEach( (input) => { 
    expectedData.push(
       {x: input.date, y: [input.open, input.high, input.low, input.close] }
       );
    });

Upvotes: 1

You can do this with .map and the exact format you provided:

data.map((d)=>({x: d.date, y: [d.open, d.high, d.low, d.close]}))

Upvotes: 0

Related Questions