Search code examples
jqueryobjecteachobject-literal

jQuery Create Object Literal Loop


I need to loop through a series of DOM elements and create an object literal with jQuery as seen below. I'm guessing this involves the usage of .each, but I'm a bit stuck on what to do next.

    '1': {
        'text': 'Maintain Compliance',
        'desc': 'blah',
        'size': 10,
        'color': '#afb0b3'
    },
    '2': {
        'text': 'lorem ipsum',
        'desc': 'blah.',
        'size': 4,
        'color': '#9b9ca0'
    },
    '3': {
        'text': 'lorem ipsum',
        'desc': 'blah',
        'size': 6,
        'color': '#c5c6c7'
    }

Solution

  • You'd use .map() to create an Array of the objects.

    var objects = $('.my_elements').map(function(i,el) {
        var $el = $(el);
        return {
            text:$el.text(),
            desc:'blah',
            size:'some_size_property_of_the_element?',
            color:$el.css('color')
        };
    }).get();
    

    The object returned from each iteration is added to the collection.

    This version of .map() actually returns a jQuery object, so you need .get() to convert to an Array.


    You could use the other $.map to create an Array directly.

    var objects = $.map($('.my_elements'), function(el,i) {
        var $el = $(el);
        return {
            text:$el.text(),
            desc:'blah',
            size:'some_size_property_of_the_element?',
            color:$el.css('color')
        };
    });
    

    Notice that the parameters are reversed from the first version. Easy to get caught on that.


    And by the way, you're not really creating an "object literal". You're just creating an object. "Object literal" is a notation used to create objects.


    Also, I've assumed by your numeric indices that you want an Array of objects. If the main structure shouldn't be an Array, then it will need to be a little different, like this...

    var objects = {};
    
    $('.my_elements').each(function(i,el) {
        var $el = $(el);
        objects[ i+1 ] = {
            text:$el.text(),
            desc:'blah',
            size:'some_size_property_of_the_element?',
            color:$el.css('color')
        };
    });
    

    This starts the numbering on 1 as shown in the question. Though I'd still be inclined to use an Array.