javascriptjsontypescriptangular6jsobject

how to convert prototype array to a json string


I have my js object/array

[Containerbox-1: Array(2)
0: "textbox-3"
1: "rediobox-4"
length: 2
__proto__: Array(0)
length: 0
__proto__: Array(0)]

Who to convert this in to a string I have used the JSON.stringify(); but i get only [] I am not sure what is the problem here.

I have defined my variable public formFieldParent = []; like this in my component.ts. And further I push elements in it dynamically

if (isNullOrUndefined(this.formFieldParent[targetId])) { 
        this.formFieldParent[targetId] = []; <--- Adding key here 
      }
this.formFieldParent[targetId].push(idNm); <-- adding values here for key

when I console it then the output is as shown above, and returns [] by using JSON.stringify(this.formFieldParent);

what should I use to get the string of it. Here is the screen shot of console enter image description here


Solution

  • I have defined my variable public formFieldParent = [];

    That's the problem. You should have used an object here, as you assign textual properties (like Containerbox-1) to it. The array stays empty (length is 0), and that's what will be shown in the JSON. Don't abuse arrays as objects!