0

I searched a while but couldn't find the answer that I want. I am have a very simple question, how to get rid of the empty objects from Map.

const friuts = [{
    apple: 'red',
    banana: 1
  },
  {
    apple: 'green',
    banana: 1
  },
  {
    apple: 'yellow',
    banana: 3
  }
]

const newObject = friuts.map(e =>
  ({ ...e.banana === 1 ? {
      apple: e.apple
    } :
      []
  })
)


console.log(newObject)

If you check the console.log it contains an empty object at the end

[
  {
    "apple": "red"
  },
  {
    "apple": "green"
  },
  {} <--- empty 
]

Also I tried undefined or below code, but just can't get rid of the empty objects.

...e.banana === 1 &&
    {
        apple: e.apple
    }

I understand this can be easily done by using other methods like filter. However, I am learning Map, so I'd like to learn how to get rid of the empty objects from map.

Sorry for if the question has been asked before. I will remove the question if it is duplicated.

1
  • 3
    The short answer is that you can't. And even if someone post a cryptic answer with a crazy way for skipping elements using map only, it will make little sense, since the code should be readable. For each task you need to use the correct tool, and the tool here is reduce. Commented Dec 2, 2022 at 5:13

2 Answers 2

1

You can't do it with map, which returns one result element per input element.

You can either add a filter to the chain or use flatMap instead:

const fruits = [
  {
    apple: 'red',
    banana: 1
  },
  {
    apple: 'green',
    banana: 1
  },
  {
    apple: 'yellow',
    banana: 3
  },
]

console.log(fruits.filter(e =>
  e.banana === 1
).map(e =>
  ({
    apple: e.apple
  })
));

console.log(fruits.flatMap(e =>
  e.banana === 1
    ? [{
      apple: e.apple
    }]
    : []
));

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

Comments

0
const newObject = friuts.map(e => {
return e.banana === 1 ? { apple: e.apple } : {}
}).filter(e => Object.keys(e).length > 0)


console.log(newObject)

Why not do this instead? It don't see a point of using spread operator here

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.