Transform objects of an array - Array.map
Tue Jun 29 2021 11:45:24 GMT+0000 (Coordinated Universal Time)
Saved by
@hisam
#object
#array
#javascript
#vanilla
let sizes = cars.map(car => {
if (car.capacity <= 3){
return "small";
}
if (car.capacity <= 5){
return "medium";
}
return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']
//create a new object if we need more values:
let carsProperties = cars.map(car => {
let properties = {
"capacity": car.capacity,
"size": "large"
};
if (car.capacity <= 5){
properties['size'] = "medium";
}
if (car.capacity <= 3){
properties['size'] = "small";
}
return properties;
});
console.log(carsProperties);
// output:
// [
// { capacity: 7, size: 'large' },
// { capacity: 5, size: 'medium' },
// { capacity: 5, size: 'medium' },
// { capacity: 2, size: 'small' },
// ...
// ]
content_copyCOPY
Comments