rnldpbln
rnldpbln

Reputation: 674

How to set another object inside another object | JavaScript

I don't know if this question's been answered yet but I'd still ask. Pretty confused over this one, and it might be simple but nonetheless, here goes:

I want to turn this already set object (meaning i have no access to it, just getting it from the server):

Object: {

    test1: 'test1',
    test2: 'test2',
    test3: 'test3'

}

to (basically just add another object inside it):

Object: {

    test1: 'test1',
    test2: 'test2',
    test3: 'test3',
    test4: 'test4'

}

Not sure if this was asked or answered before but if I can get an answer here to clarify this, it would be awesome.

Upvotes: 0

Views: 993

Answers (2)

user663031
user663031

Reputation:

basically just add another object inside it

You're not adding an object inside it; you're adding a property.

There are several ways.

Object.defineProperty(myObject, 'test4', { value: 'test4 })

This will return the object, which could be handy.

Or, of course, just

myObject.test4 = 'test4'

You can use the "merge" or "extend" features in many libraries, which would be useful if adding more than one new property:

_.extend     (myObject, { test4: 'test4' })  // Underscore
$.extend     (myObject, { test4: 'test4' })  // jQuery
Ember.merge  (myObject, { test4: 'test4' })  // Ember
Object.assign(myObject, { test4: 'test4' })  // ES6

Upvotes: 1

If you have an object like this:

people = {
    name: 'John Doe',
    age: 18
};

You can simply add one attribute to it this way:

people.hairColor = 'black';

Than your people object will be like:

people = {
    name: 'John Doe',
    age: 18,
    hairColor: 'black'
};

Upvotes: 1

Related Questions