0

I have an object literal, a:

a = {foo: 'foo'};

And I want to get b, the combination of a and {bar: 'bar'}:

b = {foo: 'foo', bar: 'bar'};

How can I do with without writing out all of the properties of a? i.e:

b = a + {bar: 'bar'};

And no, I do not want to have a be a property itself of b, as shown here:

b = {a: a, bar: 'bar'};
Blue Sheep
  • 442
  • 7
  • 16

1 Answers1

1

You can iterate through the properties of a and add them to b, like this

for (var key in a) {
    b[key] = a[key];
}

If you want to add only the properties specific to a (properties which are not inherited), you can do it like this

for (var key in a) {
    if (a.hasOwnProperty(key) {
        b[key] = a[key];
    }
}

As S McCrohan points out, if you are using jQuery, you can use jQuery.extend method to do the same.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497