JackTheKnife JackTheKnife - 6 months ago 10
jQuery Question

Accessing array of objects (or array of arrays) in Javascript

In my JavaScript I have an array of data stored in two ways

  • as an array of arrays
    data1[i++] = [id, url, val]


  • as array of objects
    data2[i++] = {id:id, url:url, val:val}

when I will output both arrays to the console I see all data which are correct.

Next I want to access them. For a first set of data I'm doing that:

var total = data1.length;
for (var j = 0; j < total; j++) {

and then for second set of that

var total = data2.length;
for (var j = 0; j < total; j++) {
console.log(data2[j].id + data2[j].gradient + data2[j].url);


but if I want to use them (data from an object)

jQuery( "#' + data2[j].id + ' .banner-bg" ).css( "background-image", data2[j].url );

it throws an error

Error: Syntax err or, unrecognized expression: # + data[j].id + .banner-bg

Where I have made a mistake?


You're just escaping your quotes wrong. Do this:

jQuery( '#' + data2[j].id + ' .banner-bg' ).css( "background-image",  data2[j].url );