In javascript I would like to bine 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 bine a
and b
as follows:
var a = { test: false, test2: { test3: false, test4: false } };
var b = { test2: { test4: true } };
// desired bined result:
{ test: false, test2: { test3: false, test4: true } }
but the actual result I get removes test3
from the nested test2
object.
In javascript I would like to bine 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 bine a
and b
as follows:
var a = { test: false, test2: { test3: false, test4: false } };
var b = { test2: { test4: true } };
// desired bined result:
{ test: false, test2: { test3: false, test4: true } }
but the actual result I get removes test3
from the nested test2
object.
- 3 $.extend() should work. show what code you tried. – yoavmatchulsky Commented Jan 31, 2012 at 11:48
- what is the rule for the final object to get test2: true, instead of test2: false? – André Alçada Padez Commented Jan 31, 2012 at 11:49
- what I need is var a = { test: false, test2: { test3: false, test4: false } }; var b = { test2: { test4: true } }; and get { test: false, test2: { test3: false, test4: true } } but I get test3 removed after – debianek Commented Jan 31, 2012 at 12:01
- possible duplicate of How does extend() work in jQuery? – user57508 Commented Jan 31, 2012 at 12:05
1 Answer
Reset to default 10var 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./jQuery.extend/
update
In your ment 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