Charles Salvan
Charles Salvan

Reputation: 3

Fill 2D array "line by line" JavaScript/NodeJS

Hello I am struggling with arrays in JavaScript/NodeJS.

Basically, here is my code:

let arr = new Array();

arr = {
  "Username" : var1,
  "Console"  : var2,
  "Pseudo"   : var3,
}

console.log(arr);

var1, 2 and 3 contains my data that is changing each time.

Let's consider for our first case:

  1. var1 is "Johnson"
  2. var2 is "ps4"
  3. var3 is "Johnson46"

The code above would display the following:

{ Username: 'Johnson', Console: 'ps4', Pseudo: 'Johnson46' }

Now if the data in var1, var2, and var3 change, it will replace the array's content with new data. So if var1 = "Dave", var2 = "xbox" and var3 = "Dave78", it will replace the current array and display:

{ Username: 'Dave', Console: 'xbox', Pseudo: 'Dave78' }

But instead I would like my code to print the follwing:

  1. { Username: 'Johnson', Console: 'ps4', Pseudo: 'Johnson46' }
  2. { Username: 'Dave', Console: 'xbox', Pseudo: 'Dave78' }

See? Without overriding the array, just adding my data in succession. "line by line" or "step by step" if you prefer, sorry I don't really know how to say that.

Upvotes: 0

Views: 82

Answers (2)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

I am going for more of a theoretical route. Maybe it will clear some of your doubt maybe it will not.

First of all, on a side note, Even though Array is technically an object but {..} is the notation for objects not arrays. If there is a object like {'0':.., '1':.., '2':..} and it has a length property then is called an array like object (thanks @Alnitak)

Now, when you are declaring an object, and adding values from variables if you're referencing an immutable object like string, number it will reference the value itself. If you're referencing say an object it will hold the object's reference and if you change the object it will change too.

For example:

const obj = {'a':'b'};

const x = {
    m: obj.a
}
console.log(x);
obj.a = 'c';
console.log(x);

This will print,

{ m: 'b' }
{ m: 'b' }

But when your code is:

const obj = {'a':'b'};

const x = {
    m: obj //referencing obj
}
console.log(x);
obj.a = 'c';
console.log(x);

It will print:

{ m: { a: 'b' } }
{ m: { a: 'c' } }

So, if you want your code to just print it then you can reference an object in your variable.

Upvotes: 0

You must push your objects to the array instead modifying it

let arr = new Array();

object1 = {
  "Username" : "Jhon",
  "Console"  : "xbox",
  "Pseudo"   : "asd",
}

arr.push(object1)

object2 = {
  "Username" : "Doe",
  "Console"  : "ps4",
  "Pseudo"   : "efg",
}

arr.push(object2)

console.log(arr);

Upvotes: 3

Related Questions