Taieb
Taieb

Reputation: 920

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
  },
  {
    ...
  },
  ...
]

Upvotes: 0

Views: 135

Answers (4)

mqliutie
mqliutie

Reputation: 408

You can use lodash

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

Upvotes: 0

code đờ
code đờ

Reputation: 615

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}[];

Upvotes: 0

veryverde
veryverde

Reputation: 454

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

Upvotes: 1

Yana Trifonova
Yana Trifonova

Reputation: 641

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

Upvotes: 1

Related Questions