ধরুন, আমাদের এইরকম একটি 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" } ] }];
আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এইরকম একটি অ্যারে নেয় এবং এটিকে নিম্নলিখিত 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" } ] } ]