user336206 user336206 - 7 months ago 17
HTML Question

Create obj out of Div contents

I have the following HTML structure:

<div id="main">
<div id="myDiv1">
<ul>
<li>Abc</li>
<li>Def</li>
</ul>
</div>
<div id="myDiv2">
<ul>
<li>Ghi</li>
<li>Jkl</li>
</ul>
</div>
</div>


I now want to extract some information and put them into an object like that:

var ob = {
'myDiv1' : [ "Abc", "Def"],
'myDiv2' : [ "Ghi", "Jkl"]
};


My approach was very inconvenient:

var obj = "{";

$('#main div').each(function() {
obj += "\"" + $(this).attr('id') + "\" : [";
$(this).find('li').each(function() {
obj += "\"" + $(this).text() + "\", ";
});
obj = obj.substring(0, obj.length - 2);
obj += "], ";
});
obj = obj.substring(0, obj.length - 2);
obj += "}";

obj = JSON.parse(obj);
console.log(obj)


As a result I got an array, but not the structure I need.

Is there a better way to create the structure?

Later, I want to pass
obj
as a parameter in an Ajax call.

Fiddle.

Answer

You can make your code much simpler by just creating an object directly. You can loop over the div elements within #main then use map() to create an array of the li text values the child div contains. Try this:

var obj = {};
$('#main div').each(function() {
    obj[this.id] = $(this).find('li').map(function() {
        return $(this).text();
    }).get()
});

console.log(JSON.stringify(obj)); // = "{"myDiv1":["Abc","Def"],"myDiv2":["Ghi","Jkl"]}"

Working example

Later, I want to pass obj as a parameter in an Ajax call.

Also note that you do not need to pass the object in JSON format to do this - you can provide an object directly to the data parameter of the AJAX request and jQuery will automatically encode and stringify it for you.

Comments