1
function A(){
   //how to alter persist to false here?
   B(obj.options);
}

function B(options){
   if(options.persist === true){ //do something }
}

I want to alter my nested object value. I can do it with one line, but what if I have many options's object? it's ugly I have to do it obj.options.a, obj.options.b, obj.options.c etc..

1
  • please add the data or part of the data as well. Commented Dec 7, 2016 at 9:56

2 Answers 2

4

Using jQuery extend function:

var object1 = { a: false, b: 1, c: 2 };
var object2 = { a: true, b: 2 };

jQuery.extend(object1 , object2 );
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, jQuery.extend( [deep ], target, object1 [, objectN ] ) If true, the merge becomes recursive (aka. deep copy).
1

If you don't want to use jQuery you can use Object.assign - it is part of ES6 and supported in most environments if you don't use a transpiler. The signature is quite similar to jQuery.extend:

Object.assign({}, object1, object2, { some: { nested: value }});

Or with ES6 you don't really need object assign, you can also write

const newObj = { ...oldObj, { keyToOverwrite: value }};

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.