krsna
krsna

Reputation: 4353

Construct an array of objects after doing a filter for an array in JavaScript

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

Answers (4)

jchung201
jchung201

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

Nina Scholz
Nina Scholz

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

Robo Robok
Robo Robok

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

Carlos1232
Carlos1232

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

Related Questions