1

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);
  }
0

1 Answer 1

5

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.

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

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.