2

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)); //[[]]
  
  } 
3
  • 4
    You're using l like it's an object, so it should be an object - let l = {}; Commented Mar 29, 2022 at 23:07
  • 3
    [] is an array not an object literal. The properties are technically being added to the array object but not in a way that JSON.stringify can understand - you want to use curly braces {} to define an object. Commented Mar 29, 2022 at 23:07
  • 1
    andrewdupont.net/2006/05/18/… Commented Mar 29, 2022 at 23:33

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.