SO-76062096

by David Thomas

JavaScript

// the initial Array of Objects:
const data = [{
    id: 1,
    name: "John",
  },
  {
    id: 2,
  },
  {
    id: 3,
  }
],

// a simple function, declared using Arrow function syntax,
// which takes one argument, an Array of Objects:
getAllKeys = (objectArray) => {

  // we return an Array formed from a Set, by use of the
  // spread syntax and an Array literal:
	return [...new Set(
        // we form the Set from the reduced Array of Objects,
        // created using Array.prototype.reduce():
        objectArray.reduce(
          // the Array.prototype.reduce() method has the
          // arguments of 'acc' (the accumulator formed
          // by the method), and the 'curr' Object (the
          // current Object of the Array of Objects):
          (acc,curr) => {
            // within the Arrow function, we simply
            // push the keys of the current Object -
            // retrieved with Object.keys - to the
            // accumulator Array, which we then flatten
            // using Array.prototype.flat():
            acc.push(Object.keys(curr));
          return acc.flat();
        // the empty Array-literal here is the accumulator
        // used within the method:
        },[]
      )
    )];
  },
// here we use the function to retrieve an Array of the
// keys from Objects in the data Array:
keys = getAllKeys(data),

// we then use Array.prototype.map() to iterate over the
// data Array and create a new Array from that Array:
newData = data.map((obj) =>{
  // we return a new Object, created using Object.fromEntries():
	return Object.fromEntries(
    // we use Array.prototype.map() to iterate over the
    // Array of Object properties:
    keys.map(
      // 'k' is the value of the current Object property
      // ('k' standing for 'key' in this case);
      // we return a new two-part Array formed from the
      // current Object property-name, and the existing
      // property-value of the current Object's property
      // of that name, or null...