0

How do I add an if statement in a return statement of this sort:

return {
    ID: select('core/editor').getEditedPostAttribute('featured_media'),
    if (ID) {
        media: select('core').getMedia( ID )
    }
};

Clearly, I can't just drop an if statement if () directly within return {}.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

1 Answers1

4

There are 2 things you can do, either use a ternary operator inline:

return {
    ID: select('core/editor').getEditedPostAttribute('featured_media'),
    media: (ID ? select('core').getMedia( ID ) : undefined)
};

or create the object and conditionally add a new property

const obj = {
    ID: select('core/editor').getEditedPostAttribute('featured_media')
};

if(ID){
    obj.media = select('core').getMedia( ID )
}

return obj
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • I guess `ID` is the property. You want `if(obj.ID){`. – jabaa Feb 08 '22 at 15:19
  • This adds the `media` property when not needed – Ruan Mendes Feb 08 '22 at 15:20
  • @JuanMendes The first one adds a property with the the value `undefined` this may or may not be a problem which is why I included the second options – Jamiec Feb 08 '22 at 15:20
  • @jabaa that doesnt make any sense. `ID` as far as I can tell is just a variable set elsewhere – Jamiec Feb 08 '22 at 15:21
  • Why would you call `select('core/editor').getEditedPostAttribute('featured_media')` if the ID already exists in a variable? If the `ID` already exists, you can create `const obj = { ID };`. – jabaa Feb 08 '22 at 15:22
  • I have seen this question asked and adding an undefined is pretty easy. The complicated thing is not adding the property, in one shot. See my comment to the answer – Ruan Mendes Feb 08 '22 at 15:22
  • @jabaa "*Why would you call select('core/editor').getEditedPostAttribute('featured_media') if the ID already exists in a variable?*" does it? It is not at all clear from OP's code. Nor is there an explanation for what `ID` *variable* contains and if it overlaps at all with the `ID` *property*. We could guess or we could avoid guessing and work with what is provided by OP. – VLAZ Feb 08 '22 at 15:26