user4403536
user4403536

Reputation:

Set array values if match exist

I'm starting to make a script for a work project, but I wonder how I can solve the problem?, and if there is a better approach of it?.

When a user invoke the script he is able to add some optimal parameters, and if they exist I want the script to replace the default value with the new value.

As in the example below it should replace the Size: 3 with 4

$(document).ready(function () {
  $("#JGallery").JGallery({
    Size: '4'
  });
});

$.fn.JGallery = function (options) {
    var obj = {
        Size: '3',
        Width: '1190'
    };
    $.each(options, function (x, y) {
        $.each(obj, function (xx, yy) {
            if (xx == x) {
                xx = y;
            }
        });
    });
    $('#testSize').html(obj.Size)
    $('#testWidth').html(obj.Width)
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="JGallery"></div>

<div id="testSize"></div>
<div id="testWidth"></div>

I ran into a wall about how to replace the values if they exist, and would be happy to be guided in the right way. Thanks

Upvotes: 0

Views: 45

Answers (2)

user5078220
user5078220

Reputation:

The easiest solution would be to use jQuery.extend https://api.jquery.com/jquery.extend/
in your example above you could write:
var obj = $.extend({}, { Size: '3', Width: '1190' }, options);

Upvotes: 0

ADreNaLiNe-DJ
ADreNaLiNe-DJ

Reputation: 4919

You need to update the obj object by using it as an associative array.

Here is a working codepen: http://codepen.io/adrenalinedj/pen/qZMwVJ

Here is the corrected part:

$.each(options, function (x, y) {
    $.each(obj, function (xx, yy) {
        if (xx == x && yy != y) {
            obj[xx] = y;
        }
    });
});

I also added the part about checking the value in the condition (eg. yy != y).

Upvotes: 1

Related Questions