Search code examples
javascriptobjectcasperjsassign

Assign children to object in casperjs


I am trying to assign to nested object (in casperjs):

    var yearz = [];
    var yearz2 = $('#form_model optgroup');
    yearz2.each(function() {
        var theyear = $(this).attr('label');        
        var theobj = {
            Year: theyear,
            Thing: [{}]
        };

        for (var i = 0; i < $(this).children().length; i++){
            theobj["Thing"].push({Name: $(this).children()[i].attr("value")});
        }

        yearz.push(theobj);
    });

this.echo(yearz) returnsnull Can you see the problem?

Best Regards

EDIT

var yearz = [];
var yearz2 = $('#form_model optgroup');
yearz2.each(function() {
    var theyear = $(this).attr('label');
    var lengthch = $(this).children().length; 
    var thisch = $(this).children();      
    var theobj = [];
    var alls = [];

    for (var i = 0; i < lengthch; i++){
        alls.push(thisch.attr("value"));
    }

    theobj = {
        Year: theyear.trim(),
        Thing: alls
    };

    yearz.push(theobj);
});

This pushes same element in alls array. But there are two of them. How can i push both of them, not the same twice?

This does not work:

for (var i = 0; i < lengthch; i++){
    alls.push(thisch[i].attr("value")); //Note [i] here.
}

Solution

  • alls.push(thisch[i].attr("value")); //Note [i] here.
    

    That does not work because [] returns a DOM, not a jQuery object and DOM does not have .attr()

    so it should be

    thisch.eq(i).val()
    

    or

    thisch[i].value
    

    You can also just use each() or map() instead of the for loop.

    var values = thisch.map( function() { return this.value; } ).get();