简体   繁体   English

在 javascript 中创建具有新结构的 object 数组副本的最佳方法

[英]Best way to create a copy of an object array with a new structure in javascript

I would like to know if there is a better option to create a copy of an object array with a new structure我想知道是否有更好的选择来创建具有新结构的 object 数组的副本

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
  }

That's a typical use case for Array#map这是 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));

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

The .map function is exactly to be used in this situations. .map function 正是用于这种情况。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM