0

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Right, of course just straight up define it as an object. funny I asked this because it wasn't working before on other projects but it worked here. Anyways, thanks :) I'll accept this answer as soon as it's possible.
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'
};

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.