ধরুন, আমাদের নিচের JSON অবজেক্ট −
আছেconst input = { "before": { "device": [ { "id": "1234", "price": "10", "features": [ { "name": "samsung", "price": "10" }, { "name": "Apple", "price": "20" } ] }, { "id": "2154", "price": "20", "features": [ { "name": "samsung", "price": "30" }, { "name": "Moto", "price": "40" } ] } ] }, "after": { "device": [ { "id": "1234", "price": "50", "features": [ { "name": "samsung", "price": "20" }, { "name": "Lenovo", "price": "30" } ] }, { "id": "2158", "price": "40", "features": [ { "name": "samsung", "price": "30" } ] } ] } };
আমাদের প্রয়োজন হল আইডি এবং এর বৈশিষ্ট্যটিকে একটি একক সারিতে গোষ্ঠীবদ্ধ করা যদি একই আইডি অবজেক্টের আগে এবং পরে থাকে।
এবং প্রয়োজনীয় আউটপুট নিম্নলিখিত ভিজ্যুয়াল উপস্থাপনা দ্বারা আরও ভালভাবে বর্ণনা করা যেতে পারে।
আমাদের এমন একটি ফাংশন লিখতে হবে যা একইভাবে ডেটাকে গোষ্ঠীবদ্ধ করে এবং সাজায়।
উদাহরণ
নিম্নলিখিত কোড -
const input = { "before": { "device": [ { "id": "1234", "price": "10", "features": [ { "name": "samsung", "price": "10" }, { "name": "Apple", "price": "20" } ] }, { "id": "2154", "price": "20", "features": [ { "name": "samsung", "price": "30" }, { "name": "Moto", "price": "40" } ] } ] }, "after": { "device": [ { "id": "1234", "price": "50", "features": [ { "name": "samsung", "price": "20" }, { "name": "Lenovo", "price": "30" } ] }, { "id": "2158", "price": "40", "features": [ { "name": "samsung", "price": "30" } ] } ] } }; const formatJSON = data => { const sub = Object.fromEntries(Object.keys(data).map(k => [k, 0])); return Object.values(Object.entries(data).reduce((r, [col, { device }]) => { device.forEach(({ id, price, features }) => { r[id] = r[id] || [{ id, ...sub }]; r[id][0][col] = price; features.forEach(({ name, price }) => { let temp = r[id].find(q => q.name === name); if (!temp){ r[id].push(temp = { name, ...sub }); }; temp[col] = price; }); }); return r; }, {})); }; console.log(formatJSON(input));
আউটপুট
এটি কনসোলে নিম্নলিখিত আউটপুট তৈরি করবে -
[ [ { id: '1234', before: '10', after: '50' }, { name: 'samsung', before: '10', after: '20' }, { name: 'Apple', before: '20', after: 0 }, { name: 'Lenovo', before: 0, after: '30' } ], [ { id: '2154', before: '20', after: 0 }, { name: 'samsung', before: '30', after: 0 }, { name: 'Moto', before: '40', after: 0 } ], [ { id: '2158', before: 0, after: '40' }, { name: 'samsung', before: 0, after: '30' } ] ]