I'm trying to create a ternary expression than when is true, i'll assign several new keys to an object. This returns an error:

const entity = {}; element.data.icon ? entity['url'] = element.data.icon.data.image[0].url entity['alt'] = element.data.icon.data.image[0].alt entity['title'] = element.data.icon.data.image[0].title : entity['url'] = '' 

I'm trying to get the equivalent to this:

const entity = {}; if (element.data.icon) { entity['url'] = element.data.icon.data.image[0].url entity['alt'] = element.data.icon.data.image[0].alt entity['title'] = element.data.icon.data.image[0].title } entity['url'] = '' 

How should I do it? if possible

2

2 Answers

Why not just use the if version? It would be more readable.

Having said that, you can use commas like so:

element.data.icon ? (entity['url'] = element.data.icon.data.image[0].url, entity['alt'] = element.data.icon.data.image[0].alt, entity['title'] = element.data.icon.data.image[0].title) : entity['url'] = ''; 

You can use the ternary to assign different complete objects:

const entity = element.data.icon ? { url: element.data.icon.data.image[0].url, alt: element.data.icon.data.image[0].alt, title: element.data.icon.data.image[0].title } : { url: "" }; 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy