0

'tI am extending two JavaScript objects where one is a variable ajaxed in from a file and the other is a simple object with user preferences.

// local prefs
var prefs = { name: "Bob Barker", show: "Price is Right" };

// ajax in default prefs with dataType: "script"
var defaultPrefs = { 
         studio: { name: "CBS", location: "Hollywood, CA" },
         producers: [ { name: "Producer1" }, { name: "Producer2" } ]
}

// merge prefs
var mergedPrefs = $.extend( prefs, defaultPrefs );

The problem is I can't access the producers or studio using prefs.producers or prefs.studio as they are Objects in the merged file. How can I get around this?

1
  • 1
    Are you saying you want to be able to access them using prefs.producers or that you do not want to access them using prefs.producers? Commented Mar 30, 2016 at 21:16

2 Answers 2

2

Try this:

var mergedPrefs = $.extend({}, prefs, defaultPrefs);

Extending an empty object will create a new copy of the original object(s).

You can also use Object.assign for the same task, however jQuery.extend also has a deep option to merge recursively whereas Object.assign is always flat (for better performance).

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

2 Comments

@MoreScratch This answer seems to do what you want, but also note that you don't need to use jQuery for this. You can also use the ES6 Object.assign function, which is functionally equivalent to $.extend.
Taken from the docs: If, however, you want to preserve both of the original objects, you can do so by passing an empty object as the target:var object = $.extend({}, object1, object2); api.jquery.com/jquery.extend
2

Try this code, but I recomend Object.assign in ES6 to don't use JQuery. Is the same:

var mergedPrefs = Object.assign({}, prefs, defaultPrefs);

Snippet with your code working without Object.assign (using $.extend):

// local prefs
var prefs = {
  name: "Bob Barker",
  show: "Price is Right"
};

// ajax in default prefs with dataType: "script"
var defaultPrefs = {
  studio: {
    name: "CBS",
    location: "Hollywood, CA"
  },
  producers: [{
    name: "Producer1"
  }, {
    name: "Producer2"
  }]
}

// merge prefs
var mergedPrefs = $.extend({}, prefs, defaultPrefs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 Comment

AS ECMA Script 6th edition, you may provide a polypill for browsers that don't support ES6. See developer.mozilla.org/en/docs/Web/JavaScript/Reference/…

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.