redGREENblue
redGREENblue

Reputation: 3126

Creating a JSON object from Javascript array

So for each checkbox selected, I am getting the associated id and depending on values there deducing the node values, which is working fine. The problem I am facing is creating a proper javascript object with values from all checkboxes.

Here's the function,

function finlizeJParams()
                    {
                        var jsonOutput=[];
                        var array =  $("input[type='checkbox']:checked").map(function(){ 

                            var str=this.id;

                            var data=[];
                            var objID=str.substring(str.lastIndexOf("c_")+2,str.lastIndexOf("_n_"));
                            var objName=str.substring(str.lastIndexOf("_n_")+3,str.lastIndexOf("_p_"));
                            var objParentID=str.substring(str.lastIndexOf("_p_")+3,str.lastIndexOf("_pn_"));
                            var objParentName=str.substring(str.lastIndexOf("_pn_")+4);

                            data['ItemID']=objID;
                            data['ItemName']=objName;
                            data['ItemParentID']=objParentID;
                            data['ItemParentName']=objParentName;
                            jsonOutput.push(data)

                            return jsonOutput;
                        }).get()

                        JSON.stringify(array);
                    }

This seems to be working as I am getting arrays when I try to print it on console, See below

0: Array[0]
    ItemParentName: "Fruit"
    ItemParentID: "7"
    ItemID: "8"
    ItemName: "Apple"
1: Array[0]
    ItemParentName: "Fruit"
    ItemParentID: "7"
    ItemID: "9"
    ItemName: "Orange"

However, if I do a JSON.stringify(jsonOutput), I get empty arrays [[],[]]? What am I doing wrong? Also, how can I group these array by parentID/Name and then convert to a JSON object?

Upvotes: 1

Views: 88

Answers (1)

Quentin
Quentin

Reputation: 943108

You are treating an array as a plain object.

While arrays inherit from objects, they are designed for numerical indexed, sequential data and only properties with numerical values will be included when you pass them through JSON.stringify.

If you want to use named keys, then use an object ({}), not an array ([]).

var data={};

Upvotes: 5

Related Questions