Reputation: 4353
I was able to filter the array but when I'm trying to create an array of objects out of the filtered data, the result appears to be undefined
. How do I construct an array of objects in the below format. Could anyone please help?
[{ brand: 'BMW'}, { brand: 'Audi'}]
Snippet
const cars = [{
name: 'BMW',
type: 'Sedan'
}, {
name: 'Audi',
type: 'SUV'
}, {
name: 'BMW',
type: 'SUV'
}]
const result = cars.filter(({
type
}) => type === 'SUV').map((car) => {
brand: car.name
})
console.log(result)
Upvotes: 0
Views: 54
Reputation: 71
You are missing a pair of parenthesis around the new implicitly returned object from the map function. This is a tricky syntax of es6.
const cars = [{
name: 'BMW',
type: 'Sedan'
}, {
name: 'Audi',
type: 'SUV'
}, {
name: 'BMW',
type: 'SUV'
}]
const result = cars.filter(({
type
}) => type === 'SUV').map((car) => ({
brand: car.name
}))
console.log(result)
Upvotes: 1
Reputation: 386670
Basically you need to wrap the object in parentheses to distinguish it from a block statement.
const
cars = [{ name: 'BMW', type: 'Sedan' }, { name: 'Audi', type: 'SUV' }, { name: 'BMW', type: 'SUV' }],
result = cars
.filter(({ type }) => type === 'SUV')
.map(({ name: brand }) => ({ brand }));
// ^^^^^^^^^^^ wrap it
console.log(result);
Upvotes: 2
Reputation: 22755
If you want to return an object literal from the arrow function, you need to enclose that object literal in parentheses to distinguish it from a code block, which also happens to be enclosed in curly braces:
result = cars.map(car => ({
brand: car.name
}));
It's funny that your code doesn't cause an error. It's just because there's a label syntax in JavaScript, so your code inside the arrow function basically creates a brand
label to a loose value of car.name
.
Upvotes: 2
Reputation: 815
For doing this you can declare a variable and return it.
const cars = [{
name: 'BMW',
type: 'Sedan'
}, {
name: 'Audi',
type: 'SUV'
}, {
name: 'BMW',
type: 'SUV'
}]
const result = cars.filter(({
type
}) => type === 'SUV').map((car) => {
let obj = {brand: car.name}
return obj
})
console.log(result)
Upvotes: -1