简体   繁体   中英

How to change json data format from array to array of objects with javascript?

I am trying to load data into ag-grid so I got the json data like this format:

{"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}}

I need it to be like this to pass it to the grid:

{"my_data":[{"labels": 1}, {"labels": 2}, ..., {"idx":"idx1"}, {"idx":"idx2"}, ...}]

Is there a fast way to do it this format or I have to loop through the data using reduce or map ?

desired format example: https://www.ag-grid.com/sample-data/monthlySales.json

I tried to load the data like this

var obj = $.parseJSON(JSON.stringify(data));
gridOptions.api.setRowData(obj.mydata.labels);

Use reduce will simplify.

 const data = { my_data: { labels: [1, 2, 3], idx: ["idx1", "idx2"] } }; const updated = Object.entries(data.my_data).reduce((acc, [key, value]) => { value.forEach(item => acc.push({ [key]: item })); return acc; }, []); const data_updated = { my_data: updated }; console.log(data_updated);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM