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.

3
  • do you want to add value to existing property of the object or to add new properties such as z: 0? Commented Jan 17, 2020 at 18:23
  • add more x values, and more y values, i want to save coordinates, its like having an array of coordinates Commented Jan 17, 2020 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) Commented Jan 17, 2020 at 18:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.