0

I was learning React and came across this code:

{this.state.sections.map(({title, imageUrl, id, size}) => (
<MenuItem key={id} title={title} imageUrl={imageUrl} size={size}/>
))}

The question is How is that possible to use destructuring inside map(), that is, I assume this is destructuring map(({title, imageUrl, id, size}) =>right?

Wertu
  • 77
  • 6
  • Why wouldn't it be possible to do in `map`? [It's just normal destructuring of parameters](https://stackoverflow.com/questions/10804982/where-can-i-get-info-on-the-object-parameter-syntax-for-javascript-functions) - how is `map` any different to not allow it? – VLAZ Mar 01 '20 at 08:42
  • map calls the provided function for each element in the array, if each item is an object, you can use destructuring. – Junius L Mar 01 '20 at 08:46
  • @JuniusL., great explanation:), thank you – Wertu Mar 01 '20 at 08:50

1 Answers1

1

Yes, it is called destructoring, specifically object destructoring.

Array.map is like a loop which provides each item of that array at the time.

Imagine those array items are objects with a lot of properties, but you need only few of them, in that case you can use destructoring to pick only what properties you need.

For example:

const array = [
  {a: 1, b: 2, c: 3, d: 4},
  {a: 5, b: 6, c: 7, d: 8},
  {a: 9, b: 8, c: 7 ,d: 6},
  {a: 5, b: 4, c: 3, d: 2}
]

// Now we will loop over those items 
array.map(item => {
   // item here is is one of the objects like this: {a: 1, b: 2, c: 3, d: 4},
   // but let's say you need only a and b properties
})

// In that case you can use destructoring
// instead of getting the entire item object you will get only a and b
array.map({a, b} => {
  // here you can use a and b as normal variables.
  // ex. for this item - {a: 1, b: 2, c: 3, d: 4}
  // a  -> 1
  // b  -> 2
})
V. Sambor
  • 12,361
  • 6
  • 46
  • 65