I am trying to use a function that works for two scenarios, it can either iterate through the key of an object in array or the array value itself. So this prints fine:
const arr1 = [{
car: 'audi'
},{
car: 'bmw'
}]
const printCars = arr1.map(({ car }) => console.log(car))
// audi
// bmw
But I dont know how to use the same function's default parameter to allow for a simple array
const arr2 = ['audi', 'bmw'];
const printCars = arr2.map(({ car }) => console.log(car));
// Obviously car is undefined
I wonder how can I do something like
const arr = ['audi', 'bmw'];
const printCars = arr.map(({ car } = car) => console.log(car));
// audi
// bmw
I don't think there's a good way to do this in just the parameter list. You can destructure on the first line of the function, and assign a default value of the whole item:
const arr2 = ['audi', 'bmw'];
arr2.forEach((item) => {
const { car = item } = item;
console.log(car);
});
Note that since you aren't creating a new array, but performing side-effects (console.log
), you should not use .map
- instead, use forEach
. .map
is only for when you need to transform every element of one array into a new element in a different returned array.
It would be possible to put the proper value into the car
variable using just the parameter list, but it's quite ugly and an abuse of default arguments, I'll put it below for informational purposes only (please don't use it):
const arr2 = ['audi', 'bmw'];
arr2.forEach((item, i, arr, { car = item } = item) => console.log(car));
The above works because forEach
only takes 3 arguments, so the 4th will be undefined
, so you can use default arguments to put something into the car
identifier conditionally.