shasha0607
shasha0607

Reputation: 123

Why is my variable not getting assigned as an array in Typescript?

I have declared a variable 'columns' like this:

 public columns:any[];

And assigned it like this:

this.columns = Array<any> (Object.keys(this.data[0]));
console.log(this.columns[0]);

The output I am getting in my console is this:

["inventoryId", "hostName", "environment", "databaseName", "applicationName", "rdbmsVersion", "asmVersion", "os", "replicationDb", "appsSupportDl", "appGrp", "dbaGrp", "dbaDl", "dbaCrqImpGrp"]

Shouldn't the console be printing only "inventoryId" as output?

Upvotes: 2

Views: 233

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

Never use the Array constructor when you're creating an array by passing in the values it should have; use an array literal instead. (But you don't want to do that either, keep reading.) Only use the Array constructor if you're passing it a single numeric argument to create an array with that length (and no entries), which is rare.

But you don't have to create an array at all in taht code; if you want an array of the keys of the object, that's what keys gives you, directly:

this.columns = Object.keys(this.data[0]);

Why your code didn't work: If you pass it multiple arguments or a single argument that isn't a number,¹ the Array constructor creates an array by putting the arguments you give it in an array. You're giving it an array as an argument, so it put that in a one-entry array as the only entry.


¹ The fact that Array does different things based on the number of arguments and potentially the type of the first argument is one of the reasons for not using it. But one of the few places it can be handy is when you're creating an array filled with a single uniform value:

const result = Array(3).fill(42); // [42, 42, 42]

The Array(3) part creates an empty array with length = 3 (a sparse array). fill then fills those missing entries with the value you give it (42 in the above).

Upvotes: 5

Related Questions