根據鍵讀取並以 JSON 格式在 JavaScript 中解析
假設我們有一個類似這樣的 JSON 陣列 −
const arr = [{ "data": [ { "W": 1, "A1": "123" }, { "W": 1, "A1": "456" }, { "W": 2, "A1": "4578" }, { "W": 2, "A1": "2423" }, { "W": 2, "A1": "2432" }, { "W": 2, "A1": "24324" } ] }];
我們需要編寫一個 JavaScript 函式,該函式接受這樣一個數組並將其轉換為以下 JSON 陣列 −
[ { "1": [ { "A1": "123" }, { "A1": "456" } ] }, { "2": [ { "A1": "4578" }, { "A1": "2423" }, { "A1": "2432" }, { "A1": "24324" } ] } ];
示例
const arr = [{ "data": [ { "W": 1, "A1": "123" }, { "W": 1, "A1": "456" }, { "W": 2, "A1": "4578" }, { "W": 2, "A1": "2423" }, { "W": 2, "A1": "2432" }, { "W": 2, "A1": "24324" } ] }]; const groupJSON = (arr = []) => { const preCombined = arr[0].data.reduce((acc, val) => { acc[val.W] = acc[val.W] || []; acc[val.W].push({ A1: val.A1 }); return acc; }, {}); const combined = Object.keys(preCombined).reduce((acc, val) => { const temp = {}; temp[val] = preCombined[val]; acc.push(temp); return acc; }, []); return combined; }; console.log(JSON.stringify(groupJSON(arr), undefined, 4));
輸出
控制檯中的輸出將是 −
[ { "1": [ { "A1": "123" }, { "A1": "456" } ] }, { "2": [ { "A1": "4578" }, { "A1": "2423" }, { "A1": "2432" }, { "A1": "24324" } ] } ]
廣告