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'
}
You’d use
.map()to create an Array of the objects.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
$.mapto create an Array directly.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…
This starts the numbering on
1as shown in the question. Though I’d still be inclined to use an Array.