How do I conditionally use data when looping over an object

I'm trying to loop over a json structure and organize the images in different divs by the tags they have but I'm only able to spit out every single key value pair sequentially. Can I have some help?

data = {
-JkDpUSlAjzp0UMsVT-s: {
image: "http://res.abc.png",
color: "red",
shape: "round"
},
-JkDwAdq19sbNrrUIsz9: {
image: "http://res.def.png",
color: "green",
shape: "square"
},
-JkEmoK59OOpFpPrPnM4: {
image: "http://ghi.png",
color: "red",
shape: "square"
}
}

$.each(data, function() {
    $.each(this, function(key, value) {

        console.log(key + " " + value); // works

            // trying to do something like this
            if(key.color == red){
                $('.div1').append('<img src="' + key.image + '">');
            }
            if(key.shape == square){
                $('.div2').append('<img src="' + key.image + '">');
            }

    });
});

Upvotes: 0

Views: 19

Answers (1)

bvaughn
bvaughn

Reputation: 13487

I'm probably missing the point of your question but why not simplify what you've got to...

$.each(data, function() {
  if (this['color'] === 'red') {
    // Do stuff...
  }
  if (this['shape'] === 'square') {
    // Do stuff...
  }
});

In other words, you only really need to iterate on the outer collection (not on the key-value pairs).

Upvotes: 1

Related Questions