0

I would like to know if there is a better option to create a copy of an object array with a new structure

Actually I do this (typescript):

const carModels = (carList: Array<CarModel>): Array<SelectValues> => {
    const cars: Array<SelectValues> = []

    carList.forEach((car: CarModel) =>
      cars.push({
        value: `/api/modeles/${car.id}`,
        label: car.libelle,
      })
    )

    return cars
  }
1

3 Answers 3

2

That's a typical use case for Array#map

const carModels = (carList: CarModel[]): SelectValues[] =>
  carList.map((car: CarModel) =>
  ({
    value: `/api/modeles/${car.id}`,
    label: car.libelle,
  }))

const carList = [
 {id: 1, libelle: 1},
 {id: 2, libelle: 2}
]

const carModels = carList =>
  carList.map(car =>
  ({
    value: `/api/modeles/${car.id}`,
    label: car.libelle,
  }));

console.log(carModels(carList));

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

Comments

1

The .map function is exactly to be used in this situations. So you could do something like this...

const parseCarModel = (car: CarModel) => ({
    value: `/api/modeles/${car.id}`,
    label: car.libelle,
});

const cars: Array<SelectValues> = carList.map(parseCardModel);

Comments

1

You can use map(). But for such a simple task, I don't think there is a better way than the other options.

const carList = [
 {id: 1, libelle: 1},
 {id: 2, libelle: 2}
]

const cars = carList.map(x => (
  {
    value: `/api/modeles/${x.id}`,
    label: x.libelle
  }
))

console.log(cars);

1 Comment

There's no need for the curly braces and return statement

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.