1

For a given name that I'm getting from an API (for example "large_banner"), I need to import the corresponding component (in this case, "LargeBanner") in my application.

So I created an array connecting each API name to each component name:

componentNames: [
  { index: 'ButtonSection' },
  { large_banner: 'LargeBanner' },
  { small_banner: 'SmallBanner' }
]

Given "large_banner" (for example), how do I get "LargeBanner" in this array? Is there a simple way to achieve that in ES6?

1 Answer 1

1

Using Array#find on componentNames, search for the array item that contains the key (for example large_banner).

Then, return the value of this property if exists:

const componentNames = [
  { index: 'ButtonSection' },
  { large_banner: 'LargeBanner' },
  { small_banner: 'SmallBanner' }
];

const getComponent = name => {
  const component = componentNames.find(c => c[name]);
  return component && component[name];
}

console.log( getComponent('index') );
console.log( getComponent('large_banner') );
console.log( getComponent('small_banner') );
console.log( getComponent('invalid') );

If you can map the names using a JSON object as follows, this would be simpler:

const componentNames = {
  index: 'ButtonSection',
  large_banner: 'LargeBanner',
  small_banner: 'SmallBanner'
};

const getComponent = name =>
  componentNames[name];

console.log( getComponent('index') );
console.log( getComponent('large_banner') );
console.log( getComponent('small_banner') );
console.log( getComponent('invalid') );

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

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.