Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append value to javascript array

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"]};
like image 544
haz Avatar asked Jun 02 '26 22:06

haz


2 Answers

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);
like image 193
Rory McCrossan Avatar answered Jun 04 '26 11:06

Rory McCrossan


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.

like image 22
Gorka Hernandez Avatar answered Jun 04 '26 10:06

Gorka Hernandez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!