2

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

2
  • add a fiddle that will make it better. Commented Aug 5, 2014 at 13:50
  • Just a side note: we normally try to reserve the $ symbol for variables that are jQuery collections. Commented Aug 5, 2014 at 13:50

2 Answers 2

2

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/

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

1 Comment

exactly what I wanted. thanks. will accept in 5 min.
1

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

3 Comments

assuming from the selector .chosen-select that it is a <select> element with multiple attribute, the .val() returns an array of selected options.
@GabyakaG.Petrioli never assume anything!
@ExplosionPills fair point, but in this case the use of .val() and the fact that he gets results as an array (he posted what he gets) make that a non-issue.

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.