কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে JSON অবজেক্ট গ্রুপ করা


মান লজিয়ে, আমাদের নিচের মতো একটি অবজেক্টের অ্যারে আছে −

const arr = [
  { 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];

আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এমন একটি অবজেক্টের অ্যারে নেয়। ফাংশনটি অবজেক্টগুলোর 'value' এবং 'type' কীগুলো মুছে ফেলবে এবং তাদের মানগুলো সংশ্লিষ্ট অবজেক্ট-এ কী-ভ্যালু পেয়ার হিসেবে যোগ করবে।

সুতরাং, উপরের ইনপুট-র জন্য আউটপুট হবে নিচের মতো −

const output = [
  { 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45}
];

আউটপুট

এটির কোড হবে −

const arr = [
  { 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];
const groupArray = (arr = []) => {
  const res = arr.reduce(function (hash) {
    return function (r, o) {
      if (!hash[o.name]) {
        hash[o.name] = { name: o.name, flight: o.flight };
        r.push(hash[o.name]);
      }
      hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
      return r;
    }
  }(Object.create(null)), []);
  return res;
};
console.log(groupArray(arr));

আউটপুট

কনসোলে আউটপুট হবে −

[
  { name: 'JON', flight: 100, uns: 12, sch: 35 },
  { name: 'BILL', flight: 200, uns: 33, sch: 45 }
]

  1. জাভাস্ক্রিপ্টে JSON টেক্সটকে JSON অবজেক্টে কনভার্ট করার পদ্ধতি

  2. জাভাস্ক্রিপ্টে অবজেক্ট ডি-স্ট্রাকচারিং

  3. জাভাস্ক্রিপ্টে WeakMap অবজেক্ট

  4. জাভাস্ক্রিপ্টে Map অবজেক্ট