0

I have an object:

var o = { dates: { dateFrom: "01DEC2012", dateTo: "02DEC2012" }, selection: "A" };

and a function:

var getSelection = function () {
   return { selection: "A,B" };
};

calling:

o.selection = getSelection();

gets me:

{ dates: { dateFrom: "01DEC2012", dateTo: "02DEC2012" }, selection: { selection: "A,B"} };

while I need:

{ dates: { dateFrom: "01DEC2012", dateTo: "02DEC2012" }, selection: "A,B" };

I know that I can fetch getSelection() result into a variable and then update o manually, but my object is a whole lot more complex, I need to to set the whole thing in one go. How do I do that?

2 Answers 2

0

You're essentially merging getSelection() into o, so you could do something like this:

var result = getSelection();

for (var key in result) {
    o[key] = result[key];
}

If you're using jQuery, you can use jQuery.extend():

var result = jQuery.extend(getSelection(), result);
Sign up to request clarification or add additional context in comments.

Comments

0

Change your getSelection method:

var getSelection = function () {
   return "A,B";
};

Edit: How about this:

o.selection = getSelection().selection;

3 Comments

sorry but the return of my function is a complex JSON.
will work, but the implementation will rely on the structure of getSelection() return, which I want to avoid.
If you're worried about undefined/null case scenarios, perhaps you can make the RHS of the assignment as a ternary operator? (To either retain the old value or take a valid value from the method call)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.