To get the source code move your mouse pointer into the source code section and press on the upper right side the copy button. This copies the source code to the clipboard and now it can be pasted and saved into your target.
/**
 * Flattens complex objects
 *
 * Original code from Muthu Krishnan
 * https://stackoverflow.com/questions/44134212
 * with modifications and additions from Stefan Schnell
 */
function flattenObject(obj) {

  var flatObj = {};

  for (var key in obj) {

    if ((typeof obj[key]) === "object" && obj[key] !== null) {

      if (obj[key] instanceof Date) {
        flatObj[key] = new Date(obj[key]);
      } else {
        var flatObject = flattenObject(obj[key]);
        if (Object.keys(flatObject).length > 0) {
          for (var flatKey in flatObject) {
            // Hint: Not every character works here
            flatObj[key + '$' + flatKey] = flatObject[flatKey];
          }
        } else {
          flatObj[key] = obj[key];
        }
      }

    } else {
      flatObj[key] = obj[key];
    }

  }

  return flatObj;

}

// Main

var obj = {
  a : 1,
  b : {
    ba : 2,
  },
  c : [1, 2, 3],
  d : [
    {
      da : ['da1', 'da2', 'da3'],
    },
    {
      db : ['db1', 'db2', 'db3'],
    },
    {
      dc : [
        {
          dca : ['dca1', 'dca2', null],
        },
      ],
    },
    null,
    undefined,
    NaN,
    0,
    '',
    ['a', 'b', ['c', 'd'], ['e', 'f']],
    [
      {
        dda : 1,
      },
      {
        ddb : 1,
      },
    ],
  ],
  e : [true, false],
  f : [[1, 2]],
  g : function() {
    return "Hello World";
  },
  h : new Date(),
  i : [],
  j : {},
  z : "End"
};

var newObj = flattenObject(obj)

System.log(JSON.stringify(newObj));

// Hint: Undefined, function and symbol values are omitted by stringify.
// Infinity and NaN, as well as the value null, are all considered null.
/* result =>
{
  "a":1,
  "b$ba":2,
  "c$0":1,
  "c$1":2,
  "c$2":3,
  "d$0$da$0":"da1",
  "d$0$da$1":"da2",
  "d$0$da$2":"da3",
  "d$1$db$0":"db1",
  "d$1$db$1":"db2",
  "d$1$db$2":"db3",
  "d$2$dc$0$dca$0":"dca1",
  "d$2$dc$0$dca$1":"dca2",
  "d$2$dc$0$dca$2":null,
  "d$3":null,"d$5":null,
  "d$6":0,
  "d$7":"",
  "d$8$0":"a",
  "d$8$1":"b",
  "d$8$2$0":"c",
  "d$8$2$1":"d",
  "d$8$3$0":"e",
  "d$8$3$1":"f",
  "d$9$0$dda":1,
  "d$9$1$ddb":1,
  "e$0":true,
  "e$1":false,
  "f$0$0":1,
  "f$0$1":2,
  "h":"2023-05-31T15:53:48.684Z",
  "i":[],
  "j":{},
  "z":"End"
}
*/



This site is part of blog.stschnell.de