skip to Main Content

I am trying to merge related objects in an array of objects based on similar properties in a specific object key "name".

I have tried the following code but did not work:

const students = [];

const obj = [{
    "name": "A. Nasila",
    "adm": "",
    "class": "4p",
    "mat": "80",
    "eng": "",
    "kis": ""
  },
  {
    "name": "A. Nasila",
    "adm": "4886",
    "class": "",
    "mat": "",
    "eng": "",
    "kis": "39"
  },
  {
    "name": "Mtu Bure",
    "adm": "",
    "class": "3L",
    "mat": "",
    "eng": "86",
    "kis": ""
  },
  {
    "name": "A. Nasila",
    "adm": "",
    "class": "",
    "mat": "",
    "eng": "75",
    "kis": ""
  },
  {
    "name": "Mtu Bure",
    "adm": "9790",
    "class": "",
    "mat": "77",
    "eng": "",
    "kis": "76"
  }
];

const groupedData = obj.reduce((acc, cur) => {
  const name = cur.name;
  if (!acc[name]) {
    acc[name] = {};
  }

  for (const key in cur) {
    acc[name][key] = cur[key];
  }

  return acc;
}, {});

const result = Object.values(groupedData);

const jsonObject = JSON.stringify(result);

const div = document.getElementById("students");

const span = document.createElement("span");
span.innerHTML = jsonObject;

div.appendChild(span);
<div id="students">
</div>

Help me get the desired output as shown below;

[
    {
      "name": "A. Nasila",
      "adm": "4886",
      "class": "4p",
      "mat": "80",
      "eng": "75",
      "kis": "39"
    },
    {
      "name": "Mtu Bure",
      "adm": "9790",
      "class": "3L",
      "mat": "77",
      "eng": "86",
      "kis": "76"
    }
]

2

Answers


  1. This should work

    <!DOCTYPE html>
    <html>
    <head>
      <title>Students</title>
    </head>
    <body>
    <div id="students">
    </div>
    <script>
    const students = [];
    
    const obj = [
      {
        "name": "A. Nasila",
        "adm": "",
        "class": "4p",
        "mat": "80",
        "eng": "",
        "kis": ""
      },
      {
        "name": "A. Nasila",
        "adm": "4886",
        "class": "",
        "mat": "",
        "eng": "",
        "kis": "39"
      },
      {
        "name": "Mtu Bure",
        "adm": "",
        "class": "3L",
        "mat": "",
        "eng": "86",
        "kis": ""
      },
      {
        "name": "A. Nasila",
        "adm": "",
        "class": "",
        "mat": "",
        "eng": "75",
        "kis": ""
      },
      {
        "name": "Mtu Bure",
        "adm": "9790",
        "class": "",
        "mat": "77",
        "eng": "",
        "kis": "76"
      }
    ];
    
    const groupedData = obj.reduce((acc, cur) => {
      const name = cur.name;
      if (!acc[name]) {
        acc[name] = {
          name: name,
          adm: cur.adm,
          class: cur.class,
          mat: cur.mat,
          eng: cur.eng,
          kis: cur.kis
        };
      } else {
        // Merge the existing object with the current object
        acc[name] = {
          name: name,
          adm: cur.adm || acc[name].adm,
          class: cur.class || acc[name].class,
          mat: cur.mat || acc[name].mat,
          eng: cur.eng || acc[name].eng,
          kis: cur.kis || acc[name].kis
        };
      }
    
      return acc;
    }, {});
    
    const result = Object.values(groupedData);
    
    const jsonObject = JSON.stringify(result);
    
    const div = document.getElementById("students");
    
    const span = document.createElement("span");
    span.innerHTML = jsonObject;
    
    div.appendChild(span);
    </script>
    </body>
    </html>
    
    

    A little explanation of what’s going on

    First off, I used the reduce method to iterate through the array of objects (obj) and group them by the name property into the groupedData object.

    If the name property is encountered for the first time, I then create a new object for it. If it has already been encountered, we merge the current object’s properties into the existing object.

    I then converted the groupedData object into an array of values using Object.values method.

    Login or Signup to reply.
  2. you can also use ??= operator ( Nullish coalescing assignment )

    const obj = 
      [ { name: 'A. Nasila', adm: '',     class: '4p', mat: '80', eng: '',   kis: ''   } 
      , { name: 'A. Nasila', adm: '4886', class: '',   mat: '',   eng: '',   kis: '39' } 
      , { name: 'Mtu Bure',  adm: '',     class: '3L', mat: '',   eng: '86', kis: ''   } 
      , { name: 'A. Nasila', adm: '',     class: '',   mat: '',   eng: '75', kis: ''   } 
      , { name: 'Mtu Bure',  adm: '9790', class: '',   mat: '77', eng: '',   kis: '76' } 
      ]; 
    
    const res = Object.entries(obj.reduce((r,o) =>
      {
      r[o['name']] ??= {};
      r[o['name']]['name']  ||= o['name'];
      r[o['name']]['adm']   ||= o['adm'];
      r[o['name']]['class'] ||= o['class'];
      r[o['name']]['mat']   ||= o['mat'];
      r[o['name']]['eng']   ||= o['eng'];
      r[o['name']]['kis']   ||= o['kis'];
      return r;
      },{})); 
    
    console.log( res )
    .as-console-wrapper {max-height: 100% !important;top: 0;}
    .as-console-row::after {display: none !important;}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search