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"]};
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With