Fluxium
Fluxium

Reputation: 110

Rendering object property value only if it exists

I have an array of objects like this getting mapped and rendered.

const items = [
  {
    id: '1',
    name: 'name',
    comment: 'text',
  },
  {
    id: '2',
    name: 'name',
  },
  etc...
]
var hasComment = items.some(item => item.hasOwnProperty('comment'));

const card = items.map(item => 
        <div key={item.id}>
            <ul className="detail">
                <li>{item.name}</li>
                {hasComment ? <li>{item.comment}</li> : ''}
            </ul>
        </div>

I want the comment to be displayed depending of the property of each individual object. I googled the above solution but as soon as any object of my array has this property it gets displayed for all, leaving some empty list items. The comment on each individual item should only be rendered, if the object actually has this property.

Hopefully it's clear what I mean.

Upvotes: 1

Views: 942

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370859

You need to put the property check inside a .filter before mapping to render:

const card = items
  .filter(item => item.hasOwnProperty('comment')
  .map(item => {
    // ...

Upvotes: 2

Related Questions