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"]};

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

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.