0

I would like to join nested objects with similar keys:

var obj1 = {
  id: 1,
  styles: {
    background: "white"
  }
};

var obj2 = {
  id: 2,
  styles: {
    border: "1px solid #ccc"
  }
};

var merged = merge(obj1, obj2);

// desired outcome
merged = {
  id: 2,
  styles: {
    background: "white",
    border: "1px solid #ccc"
  }
}

jQuery's extend method and similar ones that I've seen never concat Object properties, which is excactly what I'm looking for. Other than building this method myself, I'm hoping and quite sure there's already a solution for this..

3
  • 1
    What you just described is exactly what jQuery.extend does in deep copy mode. api.jquery.com/jQuery.extend Commented Oct 17, 2014 at 22:02
  • 1
    Click run code snippet in my answer and watch console. How is my result different from your desired outcome? Commented Oct 17, 2014 at 22:09
  • 1
    your jsbin has an extra line. var obj2 = {} Commented Oct 17, 2014 at 22:11

2 Answers 2

1

jQuery.extend does what you want.

var obj1 = {
  id: 1,
  styles: {
    background: "white"
  }
};

var obj2 = {
  id: 2,
  styles: {
    border: "1px solid #ccc"
  }
};

var merged = jQuery.extend(true, obj1, obj2);

// desired outcome
console.log(merged);
console.log({
  id: 2,
  styles: {
    background: "white",
    border: "1px solid #ccc"
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, not sure how I missed that. I don't want to import all of jQuery just for this method though.. Other than browsing the source code, know of any gists for this?
0

Here's a simple method that I wrote up which does the trick nicely and doesn't require you to import a huge library just for this functionality.

function extend(obj /* , ...source */) {
    for (var i = 1; i < arguments.length; i++) {
      for (var key in arguments[i]) {
        if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
          obj[key] = (typeof arguments[i][key] === 'object' ? extend(obj[key], arguments[i][key]) : arguments[i][key]);
        }
      }
    }
    return obj;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.