Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array created from dynamic fields in objects on JS

I need to write a function that will generate table columns based on dynamic data that comes from the server. Conditionally comes an array of objects, inside which there are fields that may differ:

{
 {
  id:1,
  water: 'water',
 }
 {
  id:2,
  fire: 'fire',
  earth: 'earth'
 }
}

. And I need to form one final data array with all these fields at the output (conditionally there are 2 objects, one has the WATER field, and the other has the FIRE and EARTH field, and the output should get one array named data, which has the fields: FIRE, EARTH and WATER). I tried to formulate, but if you have questions, I will try to write more in more detail.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const data = [
    {
     id:1,
     water: 'water',
    },
    {
     id:2,
     fire: 'fire',
     earth: 'earth'
    }
];

function generateColumns(data) {
  const columns = [];
  data.forEach((item) => {
    Object.keys(item).forEach((key) => {
      if (!columns.includes(key) && key !== 'id') {
        columns.push(key);
      }
    });
  });
  return columns;
}

const columns = generateColumns(data);

console.log(columns);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading