Ad

How To Insert A Object In An Array (as A Element )

- 1 answer

I am from C++ background. I am trying to translate a C++ code to JavaScript.

in C++ we have vector < pair < int,int > > to store pairs.

in JS i have a situation. i want to store 2D coordinates. i actually want to push new coordinates to the array.

i did like

  1. first I created a Object
const coordinate = {
   x= 9,
   y= 10
}
  1. Then i tried to push that object into the array CoordinateStorage that i want this object to get stored
CoordinatesStorage.unshift({X : coordinate.x, Y : coordinates.y});

I know this code shown above is absolutely wrong to store an object into the array. I searched out for sources but i got nothing useful. Please recommend some sources that i can refer for such translation related problems if possible.

Ad

Answer

Generally speaking, we should use the .push method for an array. There are other methods available you can find them here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array but the .push method for your case is more suitable.

Basically, as a result, we want to have something like this: [ {x: 2, y: 4 }, { x: 2, y: 4 } ] We have an array of objects.

Or we could also have an array of arrays: [[1, 2], [3, 4], [4, 6]] Not sure if it okay for your case, but maybe as an option.

Also, we could create a class Vector and we might have something like [ Vector { x: 1, y: 2 }, Vector { x: 3, y: 4 }, Vector { x: 4, y: 6 } ]

Let's take a look at the examples:

  1. Using the plain object for the vector:
    const coordinate1 = {
      x: 2,
      y: 4
    };
    const coordinate2 = {
      x: 3,
      y: 4
    };

    const coordinatesStorage = [];
    coordinatesStorage.push(coordinate1);
    coordinatesStorage.push(coordinate2);

If you will do console.log(coordinatesStorage) you will see [ { x: 2, y: 4 }, { x: 3, y: 4 } ]

  1. Using the array to store a vector:
    const coordinate1 = [1, 2];
    const coordinate2 = [3, 4];
    const coordinatesStorage = [];
    coordinatesStorage.push(coordinate1);
    coordinatesStorage.push(coordinate2);

The coordinatesStorage will be [ [ 1, 2 ], [ 3, 4 ] ]

  1. Using the Vector class:

Maybe in your case, it would be more helpful to operate with a class Vector:

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

const coordinatesStorage = [];

coordinatesStorage.push(new Vector(1, 2));
coordinatesStorage.push(new Vector(3, 4));
coordinatesStorage.push(new Vector(4, 6));

And here in the console you will see [ Vector { x: 1, y: 2 }, Vector { x: 3, y: 4}, Vector { x: 4, y: 6 } ]

Take a look at the Vector implementations in JS:

  1. https://gist.github.com/jjgrainger/808640fcb5764cf92c3cad960682c677

  2. https://github.com/maxkueng/victor/blob/master/index.js

I hope this helps. Good luck!

Ad
source: stackoverflow.com
Ad