drake035
drake035

Reputation: 2877

Getting property value by property key in array of object where each object has different property keys

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?

Upvotes: 1

Views: 22

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28404

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') );

Upvotes: 1

Related Questions