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
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);
6 Comments
jQuery.obj?jQuery.obj.array.push('four'); However you really, really should not be polluting the jQuery namespace with your own variables.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
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);