0

I have the following code to get barNames from an object bar:

const {[id]: {'name': fooName} = []} = foo || {};
const {'keywords': {[fooName]: barNames}} = bar || [];
  • Note: fooName exists, but doesn't exist in keywords as a property

I want to make barNames an empty array if an object fooName does not exist in bar.keywords. I tried to to use the OR operator but it doesn't seem to work. I don't want to use any more ternary operators like ?, :, &&, etc.

Any hints would be nice.

3
  • Why not use a ternary? Readability is a feature. Commented Jun 13, 2018 at 16:05
  • 2
    This ended up working better: const barNames = bar.keywords[fooName] || [] Commented Jun 13, 2018 at 16:08
  • It's not just working better, it's the only way it's working. bar || ... could be used only if bar were undefined. Btw, it's logical OR, not a pipe. Commented Jun 13, 2018 at 16:11

1 Answer 1

1

I think you're looking for a default initialiser:

const {[id]: {'name': fooName}} = foo || {};
const {'keywords': {[fooName]: barNames = []}} = bar || {};
//                                      ^^^^
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Initializing the barNames array to empty is the solution. thanks

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.