-1

I have the following object:

interface Colors {
  [key: string]: Colors | string
}

const colors: Colors = {
  light: {
    gray: '#aaa',
  },
  black: '#000',
}

The problem is that i need to check if the passed string value represents some color in colors object like that:

// input
const color = 'light-gray'

// what I already done to get the array of keys
const keys = color.split('-') // ['light', 'gray']

// how to check if `keys` are in `colors` object

// expected output: true

I already tried the following:

keys.every(key => key in colors) // key: light -> true, key: gray -> false

Basically I'm looking for something like this:

const lightGray = colors[...keys] // unfortunatelly won't work

Thanks in advance!

0

2 Answers 2

0

A "simple" iterative version:

const findColor = (color) => {
  const colors = {
    light: {
      gray: '#aaa',
    },
    black: '#000',
  };

  // what you've already done to get the array of keys
  const keys = color.split('-') // ['light', 'gray']

  // loop through the object

  let box = colors;

  for (let i = 0; box != null && i < keys.length; ++i) {
    box = box[keys[i]];
  }

  return box;
}

console.log(findColor('light-gray'));
console.log(findColor('light-black'));

If you're comfortable with reduce, this could become:

const findColor = (color) => {
  const colors = {
    light: {
      gray: '#aaa',
    },
    black: '#000',
  };

  // what you've already done to get the array of keys
  const keys = color.split('-') // ['light', 'gray']

  // use the keys to "open" colors

  const opener = (box, key) => {
    if (box == null) {
      return null; // avoid null[key]
    }

    return box[key];
  }

  return keys.reduce(opener, colors);
}

console.log(findColor('light-gray'));
console.log(findColor('light-black'));

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

1 Comment

Thanks, really nice and simple solution!
0

You could use https://lodash.com/docs/4.17.15#get for that, e.g.

// returns #aaa
_.get(colours, 'light-gray'.split('-'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.