简体   繁体   English

如何使用javascript将json数据格式从数组更改为对象数组?

[英]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:我正在尝试将数据加载到ag-grid所以我得到了这种格式的 json 数据:

{"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 ?有没有一种快速的方法可以做到这种格式,或者我必须使用reducemap循环遍历数据?

desired format example: https://www.ag-grid.com/sample-data/monthlySales.json所需的格式示例: 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.使用reduce会简化。

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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