how to create json obj or array from div's id's? how to create json obj or array from div's id's? json json

how to create json obj or array from div's id's?


A more concise variation of AndreasAL's answer:

var jsonObj = $(".msgid").map(function() {    var obj = { id: this.id };    obj.comments = $(".comments", this).map(function() {        return { id: this.id };    }).get();    return obj;}).get();


I came up with a different json construct as below,

jsonObj = [           {'ids': '167', 'comments': ['129', '130']},           {'ids': '166', 'comments': ['134', '136']}];

See below code if you are interested in above construct,

DEMO

var jsonObj = [];var len, comments;$('.msgid').each(function(index){    len = jsonObj.push({'ids' : $(this).attr('id')});    comments = [];    $(this).find('.comments').each (function () {        comments.push($(this).attr('id'));    });    jsonObj[len - 1]['comments'] = comments;});console.log(jsonObj);


var jsonObj = [];$('.msgid').each(function(){    var obj = {        id: this.id,        comments: []    };    $(".comments", this).each(function() {        obj.comments.push({            id: this.id        });    });    jsonObj.push(obj);});console.log(jsonObj);

this will output:

[    {        id: "167",        comments: [            {                id: "129"            },            {                id: "130"            }        ]    },    {        ....    }]