3

If one want to append to this type of array:

array = ["one","two","three"];

so it becomes,

array = ["one","two","three, "four"];

use:

array.push("four");

but how do you append here:

object = {element1: one, element2: two, array: ["one","two","three"]};

so it becomes,

object = {element1: one, element2: two, array: ["one","two","three,"four"]};
Ashish Bahl
1,4941 gold badge18 silver badges28 bronze badges
asked Mar 2, 2017 at 9:47

3 Answers 3

7

You still use push(), but on the array property of your object:

var obj = {
 element1: 1,
 element2: 2,
 array: ["one", "two", "three"]
};
obj.array.push('four');
console.log(obj);

answered Mar 2, 2017 at 9:48
Sign up to request clarification or add additional context in comments.

6 Comments

supposing instead of var obj we have jQuery.obj ?
What do you mean by jQuery.obj?
jQuery.obj = { element1: 1, ... }
Then use jQuery.obj.array.push('four'); However you really, really should not be polluting the jQuery namespace with your own variables.
I did. I then get error: Reference Error: Cant find variable array
|
3

You can update an object in place like so:

let obj = {element1: 'one', element2: 'two', array: ["one","two","three"]};
obj.array.push('four');

If you want to create a new copy of the object with the extended array, you can also do the following using the new ES6 features:

let obj = {element1: 'one', element2: 'two', array: ["one","two","three"]};
let newObject = Object.assign({}, obj, { array: [...obj.array, 'four'] });

Using the second example, you keep the original object intact and create a new copy with the updated values.

answered Mar 2, 2017 at 9:49

Comments

1

In your case the values one, two have to be strings, otherwise they will be treated as variables, and you can use push too for the object using object.array.push('four');:

var object = {
 element1: "one",
 element2: "two",
 array: ["one", "two", "three"]
};
object.array.push('four');
console.log(object);

answered Mar 2, 2017 at 9:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.