user428745
user428745

Reputation: 853

Length of array in Typescript - access members

I have a declared type

type Vehiculo={
  [key: string]: string;
};

let allCars:Vehiculo = {Ford: "Ka", GM:"Sonic", Audi:"A4"};

How can I get the length of this array?

Definitely, allCars.length is not right

Upvotes: 0

Views: 5589

Answers (2)

saivishnu tammineni
saivishnu tammineni

Reputation: 1242

You need to create an array to get it's length. The syntax you have creates just an object.

class Vehiculo { // represents one vehicle
   name: string;
   model: string;
}

let allCars = Vehiculo[] = [ {name: 'Ford', model: 'KA},  {name: 'Audi', model: 'A4}, ...so on];

console.log(allCars.length); // will print number of cars

Upvotes: 1

JeffryHouser
JeffryHouser

Reputation: 39408

You can get the length of an array in JavaScript using

arrayVariable.length

Roughly like this:

arrayVariable = [1, 2, 3, 4, 5]
console.log(arrayVariable.length);

--

In your code you have not created an array. allCars is an object.

You could get the number of properties in your custom object using Object.keys():

var numberOfKeys = Object.keys(allCars).length;

If you need this, I have concerns about the underlying data model, though.

--

You could also use a map data structure instead of an object and then use the size property.

let allCars = new Map();
allCars.set('Ford, 'Ka);
allCars.set('GM', 'Sonic');
allCars.set('Audi', 'A4');
console.log(allCars.size);

But, I think this is going down a very different route than the code you already shared.

Upvotes: 1

Related Questions