1

The following works great in my function:

console.log(theme.colors.blues[1]);

I'm trying to make the last part dynamic like so:

const getColor = (theme, passedColorProp) => {
  console.log(theme.colors.[passedColorProp]);
};

getColor("blues[1]");

This is currently erring with:

Module build failed: SyntaxError: Unexpected token (15:27)**

How can I make this work?

2 Answers 2

3

You're almost there, you access a property dynamically exactly how you've done it except you don't need the extra dot.

const getColor = (theme, passedColorProp) => {
  console.log(theme.colors[passedColorProp]);
};

Note that this works for a SINGLE property, but you can't nest it as you have in your example, for that you'll need to use two different variables:

const getColor = (theme, passedColorProp, id) => {
  console.log(theme.colors[passedColorProp][id]);
};

const theme = { colors: { blues: ['something', 'something else'] } };

getColor(theme, 'blues', 1); // 'something else'
Sign up to request clarification or add additional context in comments.

2 Comments

is there a way I can still pass "blues[1]" and then use getColor to determine the two properties?
As Ori Drori says, you'll have to use regex or string split to extract the keys and loop over the properties one at a time.
1

Use String.match() with a regex to extract the keys, then iterate them with Array.reduce() to get the values:

const theme = {
  colors: {
    blues: ['blue0', 'blue1']
  }
};

const getColor = (theme, passedColorProp) => {
  const keys = passedColorProp.match(/[^\[\].]+/g); // match a sequence of everything but [ ] or .
  
  return keys.reduce((r, k) => r[k], theme);
};

console.log(getColor(theme, 'colors.blues[1]'));

2 Comments

Thanks but that is erring w Cannot read property '1' of undefined
That will happen if theme.colors.blues is returning undefined. As you can see it works in the snippet.

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.