简体   繁体   中英

Modify all object inside an array of objects

I have an Array of objects like this :

let cars = [
  {
    "color": "purple",
    "type": "minivan",
    "registration": new Date('2017-01-03'),
    "capacity": 7
  },
  {
    "color": "red",
    "type": "station wagon",
    "registration": new Date('2018-03-03'),
    "capacity": 5
  },
  {
    ...
  },
  ...
]

I want to make a change on all objects and return this array without unnecessary information ( I don't need to get the type and registration ) and have my array of objects like this:

let cars = [
  {
    "color": "purple",
    "capacity": 7
  },
  {
    "color": "red",
    "capacity": 5
  },
  {
    ...
  },
  ...
]

Use forEach :

 cars.forEach(car => { delete car.registration delete car.type })

Alternatively, if you want to create a new array, you can use the map function:

   const newCars = cars.map(car => {
     return { color: car.color, capacity: car.capacity }
    })

Here is an answer. You can use it for typescript too.

 let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, ] let newCars = cars.map(function (car) { return {"color" : car.color, "type": car.type}; }); console.log(newCars);

You can iterate over each item in the array, and remove what you don't need. But that's just Javascript. For Typescript, if you want to update the type of the array as well, you may use casting:

const newCars = cars.map(car => {
  delete car.registration;
  delete car.type;
  return car;
}) as {color: string; capacity: number}[];

你可以使用lodash

_.map(cars, _.partialRight(_.pick, ['color','capacity']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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