In javascript I would like to combine two objects into one. I got
{
test: false,
test2: false
}
and
{
test2: true
}
I tried to use $.extend
, $.merge
but all I get as an output is
{
test2: true
}
How to get output like this
{
test: false,
test2: true
}
EDIT: Actually I have nested objects. What I need is to combine a
and b
as follows:
var a = { test: false, test2: { test3: false, test4: false } };
var b = { test2: { test4: true } };
// desired combined result:
{ test: false, test2: { test3: false, test4: true } }
but the actual result I get removes test3
from the nested test2
object.
var a = {
test: false,
test2: false
};
var b = {
test2: true
};
var c = $.extend(a, b);
This will overwrite all properties on object a
with a result of:
{
test: false,
test2: true
}
If you want a new, fresh object call .extend
like so:
var c = $.extend({}, a, b);
This will do the same job, but it leaves object a
untouched and creates a new object. See http://api.jquery.com/jQuery.extend/
update
In your comment you updated the object structures. Well, what you need there is a such called "deep clone". This is just one more parameter for the $.extend()
call, like so:
var c = $.extend(true, a, b); // a gets overwritten
var c = $.extend(true, {}, a, b); // new object is created
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With