0

I want to add more elements dynamically to an array that has a named structure, I have (this works):

var v = [{
  x: 0,
  y: 0
}];

It initializes the structure with 1 element with 2 values, but, I want to add more elements later in the page, something like:

v.x.push(2); // something like this would insert a new element and give value of 2 to x of the new element.

Can anyone help me with this, using pure JavaScript? Thanks.

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
Vega_Ska
  • 21
  • 5
  • do you want to add value to existing property of the object or to add new properties such as `z: 0`? – Calvin Nunes Jan 17 '20 at 18:23
  • add more x values, and more y values, i want to save coordinates, its like having an array of coordinates – Vega_Ska Jan 17 '20 at 18:24
  • I don't think you can do it with native JS methods. IMO best solution would be some abstracted function i.e. `const pushCoord = (coordArr, coordObj = {}) => [...coordArr, { x: 0, y: 0, ...coordObj}]` - this handles case if there is only one coordinate given and defaults other to 0 (or if there are no arguments given) – Piekarski D Jan 17 '20 at 18:42

1 Answers1

1

You can use the JavaScript Array.prototype.push method, e.g.

let v = [{
  x: 0,
  y: 0
}];
v.push({
  x: 2
});
console.log(v);
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34