jQuery: asigne HTML a una matriz de objetos javascript

Any suggestions how to map the following HTML, to get the JS array of object as per below example?

<ul>
    <li class="header">Header</li>
    <li><span>val1</span></li>
    <li><span>val2</span></li>
    <li><span>val3</span></li>
    <li class="header">Another Header</li>
    <li><span>val4</span></li>
    <li><span>val5</span></li>
</ul>

JS array of objects:

    [{
        "header": "Header",
        "values": ["val1", "val2", "val3"]
    },
    {
        "header": "Another Header",
        "values": ["val4", "val5"]
    }]

This is how far I got myself:

var els = $('ul > li');
var obj = [];
els.each(function(index, item) {
    if ($(item).hasClass("heading")) {
        // maybe push this object with a heading into an array, 
        // then add to the object on following iterations and create next object when next .heading
    }
});

preguntado el 28 de mayo de 14 a las 13:05

2 Respuestas

As you said in your question, you want to mapa you html. So use .map!

This code can do it :

var arr = $('.header').map(function(){
    var obj = {}
    obj.header = $(this).text();

    obj.values = $(this).nextUntil('.header').map(function(){
        return $(this).text();
    }).get()

    return obj;
}).get()

Violín : http://jsfiddle.net/2UDwc/7/

contestado el 28 de mayo de 14 a las 13:05

A somewhat less elegant solution than Karl-André Gagnon provided, without using map:

var arr = [];
var valuesArray = [];
var obj = {};

$('li').each(function(index, item) {   
    if ($(item).hasClass('header')) {
        // If not the first section of header / values
        if(index > 1) {
            // Add values to the final array
            obj.values = valuesArray;
            arr.push(obj);

            // Reset the vars
            obj = {};
            valuesArray = [];
        }

        // Add header to the current object
        obj.header = $(item).text();
    } else {
        // Add values
        valuesArray.push($(item).text());
    }
});

// Add the last object to the array
obj.values = valuesArray;
arr.push(obj);

console.log(arr);

http://jsfiddle.net/XXKKr/3/

contestado el 28 de mayo de 14 a las 14:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.