Devalor
Devalor

Reputation: 55

overwrite object value in javascript

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

Upvotes: 1

Views: 1236

Answers (2)

tmaximini
tmaximini

Reputation: 8503

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 }};

Upvotes: 1

Faouzi Oudouh
Faouzi Oudouh

Reputation: 820

Using jQuery extend function:

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

jQuery.extend(object1 , object2 );

Upvotes: 4

Related Questions