ShaneKm
ShaneKm

Reputation: 21328

How to put array of objects into new Json object

I have several drop down lists on my page. Based on the selection of these drop downs, I would like to build resulting Json object that looks like this:

{"list":{"city":["1","2","3"],"businessName":["City1","AnotherCity"]}}

Dropdowns event here:

    $(".chosen-select").each(function () {
        $id = this.id;
        $value = $(this).val();
    });

Of course I would like this to be as generic as possible therefore I'm getting $id (which in my case is "city" and "businessName", however it may be different on another page.

$value = $(this).val();

is of course array of selected values ie: "["1","2","3"];

I've tried this but it's not what I want

    var jsonObj = {
         list: []
    };

    $(".chosen-select").each(function () {
        $id = this.id;
        $value = $(this).val();

        var obj = {};
        obj[$id] = $value;
        jsonObj.list.push(obj);
    });

which results in this:

{"list":[{"city":["2","3"]},{"businessName":["KrakVenue1","KrakVenue3"]}]}

and NOT what I want.

How would I do it? thanks

Upvotes: 2

Views: 83

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191729

jsonObj.list should be the object you want and not an array, so you shouldn't push to it.

if (!jsonObj.list.hasOwnProperty(id)) {
    jsonObj.list[id] = value;
}
else {
    // key already exists.  What should you do with it?
    // if `value` is another array, you can use `.concat`
}

It seems like value should be an array, but they are individual values and you want to treat them as an array, use:

if (!jsonObj.list.hasOwnProperty(id)) {
    jsonObj.list[id] = [];
}
jsonObj.list[id].push(value);

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Since you want your list to be an object, do not create it as an array.

var jsonObj = {
     list: {}
};

$(".chosen-select").each(function () {
    var id = this.id,
        value = $(this).val();

    jsonObj.list[id] = value;
});

Demo at http://jsfiddle.net/gaby/4f43Q/

Upvotes: 2

Related Questions