0

Here's what I have....

settings: Object
color: "#858789"
cursor: "cursors/coin.png"
height: 100
image1: "images/slide3.png"
image2: "images/slide5.png"
image3: "images/slide5.png"
image4: "images/slide2.png"
image5: "images/slide7.png"
image6: "images/slide6.png"
image7: "images/slide6.png"
image8: "images/slide1.png"
image9: "images/slide1.png"
imageCover: "images/scratchimg2.gif"
overlay: "none"
realtimePercent: true
scratchDown: null
scratchMove: function (e, percent)
scratchUp: null
size: 10
width: 100

What I NEED/WANT to do is simply access the images...

I'm using UNDERSCORE to filter through and populate an array with ONLY image1 - image9. The rest of the junk I could care less about.

Any ideas?

Here's my underscore code:

        //Populate the image array
        imgID = "image" + (parseFloat(i) + 1);

        var imgName = _.filter({imgID: "images/"}, function(imgnmid) {

            imgArray.push(imgnmid)
            return imgnmid = "images/";

        });

Yeah, I know, it's a mess...

This is inside a closure function

like this:

 (function($)
 {
   $.fn.someFuncName = function(option, settings)
   {


    .....

  }

})(Jquery);

thanks...

Peter The Angular Dude
  • 1,112
  • 5
  • 26
  • 53

2 Answers2

1

How about this? Fairly simple iteration over the object's keys. You could probably use underscore as well, but I don't think you need it.

Live Demo

JS

var obj = {
    settings: {},
    color: "#858789",
    cursor: "cursors/coin.png",
    height: 100,
    image1: "images/slide3.png",
    image2: "images/slide5.png",
    image3: "images/slide5.png",
    image4: "images/slide2.png",
    image5: "images/slide7.png",
    image6: "images/slide6.png",
    image7: "images/slide6.png",
    image8: "images/slide1.png",
    image9: "images/slide1.png",
    imageCover: "images/scratchimg2.gif",
    overlay: "none",
    realtimePercent: true,
    scratchDown: null,
    scratchMove: function (e, percent){},
    scratchUp: null,
    size: 10,
    width: 100 
}; 

function extractImages(obj){
    var imgArray = [], 
        num = 0; 

    //Iterate over the object's keys (no need for underscore to do this). 
    for(var key in obj){

        //http://stackoverflow.com/a/10003709/402706
        //Get the number off the key (if there is one)
        num = parseInt(key.replace( /^\D+/g, ''), 10);  

        //is the text 'image' part of the key and is number 1-9
        if(key.indexOf('image') > -1 && num > 0 && num < 10){
            imgArray.push(obj[key]); 
        }
    }
    return imgArray; 
}

alert(extractImages(obj)); 
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
0

You can do this:

var i = 1;
_.filter(images, function (value, index) { // images is your full object
    if ( 'image' + i == index ) {
        imgArray.push(value); // push value
        ++i;
    }
});

Demo

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64