0

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

1
  • 11
    That's not an array, it's a plain object. If you want the number of entries you can do Object.keys(allCars).length Commented Jan 9, 2022 at 4:42

2 Answers 2

1

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.

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.