5

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 that array being hard coded in my script I need to create that dynamically from a set of HTML unordered lists that are generated from the system so the markup would 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 would need:

var arrayList = new Array (that has been created)

How can I do this so that a new array object is created and it doesn't just see the output as a text string?

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
dbach
  • 163
  • 3
  • 12

2 Answers2

5

First, for more flexibility, I'd suggest you modify your markup to store the list item keys in data attributes:

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

From there, you can use map() to build your objects:

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

You can see the results in this fiddle.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
2

Try this.

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 will hold the array of your associative objects and DTO will hold the JSON string of that array.
Choose whatever you need.

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

P.S: Please add reference to json2.js for browsers that do not have JSON support ( if you use JSON.stringify )

naveen
  • 53,448
  • 46
  • 161
  • 251