Search code examples
javascriptimageobject-literal

How can I create an if/elseif/else statement based on an object literal in javascript


I would like to have an if/else if/else statement based on an object literal. The object literal will be user generated and so I will not know how long it will be, though I will know the key/value pairs naming scheme.

For example, I have some code that gets the viewport width and a function to update img src attribute below

vpwidth =  window.innerWidth;

function modifyImgSrc (srcModifier) {
    src = src.replace(".jpg", srcModifier + ".jpg");
    src = src.replace(".png", srcModifier + ".png");
    src = src.replace(".gif", srcModifier + ".gif");
};

Then I have my object literal

var brkpnts = [
   {width: 320, srcmodifier: '-s'},
   {width: 768, srcmodifier: '-m'},
   {width: 1024, srcmodifier: '-l'},
];

And I want to generate an if statement based of the object literal

if ( vpwidth <= brkpnts[0].width ) {
    modifyImgSrc(brkpnts[0].srcmodifier);
}
else if ( vpwidth <= brkpnts[1].width ) {
    modifyImgSrc(brkpnts[1].srcmodifier);
}
else {
    modifyImgSrc(breakpoints[2].srcmodifier);
}

Though since the object literal can be modified by the user, how can I generate an if/else if/else statement to match what the user adds to the object literal. For example, the may have more than 3 key/value pairs.

var breakpoints = [
    {width: 320, srcmodifier: '-xs'},
    {width: 534, srcmodifier: '-s'},
    {width: 768, srcmodifier: '-m'},
    {width: 1024, srcmodifier: '-l'},
    {width: 1440, srcmodifier: '-xl'}
];

In that case, I would want an if statement that looked like this.

if ( vpwidth <= brkpnts[0].width ) {
    modifyImgSrc(brkpnts[0].srcmodifier);
}
else if ( vpwidth <= brkpnts[1].width ) {
    modifyImgSrc(brkpnts[1].srcmodifier);
}
else if ( vpwidth <= brkpnts[2].width ) {
    modifyImgSrc(brkpnts[1].srcmodifier);
}
else if ( vpwidth <= brkpnts[3].width ) {
    modifyImgSrc(brkpnts[1].srcmodifier);
}
else {
    modifyImgSrc(breakpoints[4].srcmodifier);
}

Is this possible? If so, how, and is this the best way to achieve this?


Solution

  • Loop through the array:

    var modified = false;
    for(var i = 0, len = brkpnts.length; i < len; i++) {
        if(vpwidth <= brkpnts[i].width) {
            modifyImgSrc(brkpnts[i].srcmodifier);
            modified = true;
            break;
        }
    }
    
    // Use the biggest one if vpwidth larger than all
    if(!modified) {
        modifyImgSrc(brkpnts[brkpnts.length - 1].srcmodifier);
    }
    

    Edit: Though, Xander is correct in his comment, you should probably use media queries instead.