0

Datatype of stack id either can be an array or a string.

In the below code stack[0].id is Array and stack[1].id is string.

Issue is stackConfig is undefined when id is returned as array.

How do i handle this dynamically?

let stack = [{id:['stack1','stack2']},{id:'stack2'}]
let stackConfig = this.stackConfigs.find(c => c.id === selectionId);
3
  • What is stackConfigs ? Commented Mar 5, 2018 at 8:10
  • stackConfig is an object Commented Mar 5, 2018 at 8:14
  • 1
    Just check if typeof c.id === 'string' to distinguish between the cases Commented Mar 5, 2018 at 8:15

2 Answers 2

2

You could try something like this:

let stack = [{id:['stack1','stack3']},{id:'stack2'},{id:'stack4'}]
let selectionId = 'stack2';
let stackConfig = stack.find(c => { 
  if(Array.isArray(c.id)) { if (c.id.indexOf(selectionId) != -1) return true;}
  else { return c.id === selectionId }
  return false;
});
console.log(stackConfig);

Sign up to request clarification or add additional context in comments.

Comments

0

The first thing you should do is check whether c.id === selectionId is true at any point. This might never be true, hence why it is undefined.

You could try to handle having the selectionId also undefined as follows:

if (c.id.indexOf(selectionId) != -1) return true;

Comments

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.