Peter Hansen Peter Hansen - 2 years ago 107
Javascript Question

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


$(document).ready(function () {
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;

<script src=""></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

Answer Source

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

Here is a working codepen:

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download