I have a use case to create a table with dynamic data including header names. I've tried multiple ways to reconstruct the array from the API response but still can't develop it.
Receive the array from the response as follows
[ { "category": "Emergency services", "code": "RMY 90", "limit": "9032", "OT": "4124" }, { "category": "Pediatrician", "code": "RMY 80", "limit": "1232", "OT": "9412" }, { "category": "Neurology", "code": "RMY 70", "limit": "6423", "OT": "7312" } ]
Grid expected array
[ { "item": "Block Code", "Emergency services": "RMY 90", "Pediatrician": "RMY 80", "Neurology": "RMY 70" }, { "item": "Total Capacity", "Emergency services": "9032", "Pediatrician": "1232", "Neurology": "6423" }, { "item": "OT Capacity", "Emergency services": "4124", "Pediatrician": "9412", "Neurology": "7312" } ]
Table example
I've tried using Object.keys() and map but can't construct the array correctly. Since the code is located on the client system, I cannot share it. Please help me rebuild the array.
My code is
const rowList = ["Block Code", "Total Capacity", "OT Capacity"]; let arr = []; const dumming = rowList?.forEach(item => { for (const [key, object] of Object.entries(responseData)) { let x = []; Object.keys(object)?.forEach(item => { x.push(object[item]); }); // console.log('rrrr', x); } let val = responseData.map((ned, index) => { let x = {}; Object.keys(object)?.forEach(item => { x = ned[item] }); // let cor = Object.entries(ned).map(([key, leaf]) => key+leaf); return { id: `${ index }-${ item }`, name: item, ...x }; }); arr.push(val); }); console.log(arr);
I'm not sure if this is correct. In trouble
The idea of using rowList is good, but it assumes some key ordering in the input object (when you later need to associate data with each label), which is generally a bad idea relying on something in a normal object order.
However, your
rowList
does nothing: although you iterate over it, your code never uses theitem
(it defines otheritem
variables ).Secondly, there is an unknown variable
object
in the.map
callback.I don't understand why you generate an object with
id
andname
keys and generate a string in the format${ index }-${ item }
Because this doesn't match anything in your question.The following is what I recommend: