Skip to content
Advertisement

How to convert an array with data objects to just an array with strings with javascripts?

How to convert an array with data objects to just an array with strings with javascripts. This is the data set below

const Cars = [
      { carTypes: 'Cadillac' },
      { carTypes: 'Jaguar' },
      { carTypes: 'Audi' },
      { carTypes: 'Toyota' },
      { carTypes: 'Honda' },
    ];

This is the results i would like to get const models = ['Cadillac', 'Jaguar', 'Audi', 'Toyota', 'Honda'];

I tried this below but it didn’t work

 function OnFucTap() {
    const Cars = [
      { carTypes: 'Cadillac' },
      { carTypes: 'Jaguar' },
      { carTypes: 'Audi' },
      { carTypes: 'Toyota' },
      { carTypes: 'Honda' },
    ];

    const models = Cars.carTypes.split(',');

    console.log(models);
    alert(models);
  }

Advertisement

Answer

Use map() to access each object’s carTypes element.

const models = Cars.map(car => car.carTypes);

If carTypes could contain a comma-separated list of manufacturers, you can use split() on the property and flatMap() to concatenate all of them.

const models = Cars.flatMap(car => car.carTypes.split(','));

BTW, names like Toyota and Honda are makes. Models are Camry and Accord.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement