'Data from the object doesn't convert when using JSON.stringify

I'm stuck in this weird issue that I'm having hard time in understanding what's doing on. When a button is clicked it calls the function onSubmit. What onSubmit function should do is stringify is the object to JSON however for me this doesn't happen. The result I get when I console.log(JSON.stringify(obj)); is [[]]. When I console.log(obj); I can see the object.

I was not able to replicate the same issue in playcode.io and codesandbox.io

  async function onSubmit() {
    let l = [];
    l["Channel"] = undefined;
    l["MetricsData"] = [
      { id: 1, name: "CPA", year: "" },
      { id: 2, name: "Average Gift", year: "" },
      { id: 3, name: "Average Gift Upgrade %", year: "" }
    ];

    let obj = [];
    l.Channel = 1;
    obj.push(l);

    console.log(obj);
    console.log(JSON.stringify(obj)); //[[]]
  
  } 


Solution 1:[1]

As others have pointed in comments, you're instantiating l as an array and then attempt populating named keys (Channel, Metricsdata).
Note: Technically, arrays are objects, but they're special objects (their keys are intended to be numeric and they also have a few extra props and methods, specific to arrays - e.g: length, pop, push, slice, etc...). Use the link above to read more about arrays.

What you need to do is use l as an object (e.g: {}):

const l = {
  Channel: 1,
  MetricsData: [
    { id: 1, name: "CPA", year: "" },
    { id: 2, name: "Average Gift", year: "" },
    { id: 3, name: "Average Gift Upgrade %", year: "" }
  ]
};

// Uncomment any of the following:

// console.log('object:', l);
// console.log('stringified object:', JSON.stringify(l));

const items = [];
items.push(l);
// console.log('items:', items);
// console.log('first item:', items[0]);

console.log(JSON.stringify(items));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1