0

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
  },
  {
    ...
  },
  ...
]
3
  • Hint. Use map function. Commented Jun 25, 2021 at 7:53
  • Please share whatever you have tried. Even if you feel it is extremely wrong. Commented Jun 25, 2021 at 7:57
  • cars.map(({color,capacity}) => ({color, capacity})) Commented Jun 25, 2021 at 7:58

4 Answers 4

1

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

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

Comments

1

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

2 Comments

I tried to run the second one it's always returning Undefined
Ah sorry, my bad! I used forEach again instead of map. It should work now
0

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

Comments

0

You can use lodash

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

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.