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.
>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);