0

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)

4 Answers 4

2

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.

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

Comments

2

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

Comments

1

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)

Comments

-1

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)

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.