How to create jQuery associative array from unordered HTML list

Currently in my jQuery script I have a hard coded array:

var arrayList = [
    {"id":"1","category":"foo1","title":"bar1","image":"images/foobar1.gif"},
    {"id":"2","category":"foo2","title":"bar2","image":"images/foobar2.gif"},
    etc....
];

Instead of having this array hardcoded in my script, I need to create it dynamically from a set of unordered HTML lists that are generated from the system, so the markup will be:

<ul>
    <li>1</li>
    <li>foo1</li>
    <li>bar1</li>
    <li>images/foobar1.gif</li>
</ul>

<ul>
    <li>2</li>
    <li>foo2</li>
    <li>bar2</li>
    <li>images/foobar2.gif</li>
</ul>

etc....

I will need:

var arrayList = new array (which was created)

How can I do this to create a new array object, and it does not just see the output as a text string?

+5
source share
2 answers

Try it.

var items = [];
$("ul").each(function(){
    var item = {};
    var lis = $(this).find("li");
    item.id = lis.get(0).innerHTML;
    item.category = lis.get(1).innerHTML;
    item.title = lis.get(2).innerHTML;
    item.image = lis.get(3).innerHTML;
    items.push(item);
});

var DTO = JSON.stringify(items);

items , DTO JSON .
, .

: http://jsfiddle.net/naveen/yA54G/

PS: json2.js , JSON ( JSON.stringify)

+2

-, , data:

<ul>
    <li data-key="id">1</li>
    <li data-key="category">foo1</li>
    <li data-key="title">bar1</li>
    <li data-key="image">images/foobar1.gif</li>
</ul>

<ul>
    <li data-key="id">2</li>
    <li data-key="category">foo2</li>
    <li data-key="title">bar2</li>
    <li data-key="image">images/foobar2.gif</li>
</ul>

map() :

var arrayList = $("ul").map(function() {
    var obj = {};
    $("li", this).each(function() {
        var $this = $(this);
        obj[$this.data("key")] = $this.text();
    });
    return obj;
}).get();

.

+5

All Articles