JsCoder
JsCoder

Reputation: 1733

Setting object property without creating additional nesting level

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?

Upvotes: 0

Views: 39

Answers (2)

Blender
Blender

Reputation: 298136

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

Upvotes: 1

Vinod Vishwanath
Vinod Vishwanath

Reputation: 5891

Change your getSelection method:

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

Edit: How about this:

o.selection = getSelection().selection;

Upvotes: 1

Related Questions