0

say I have a dict like this:

colors = {
  green: {
    light: "lightgreen",
    dark: "darkgreen",
  },
  blue: {
    light: "lightblue",
    dark: "darkblue",
  }
}

How can I index into this with ONE key, like "green.light". I tried colors["green.light"], but it didn't work.

A Paul
  • 8,113
  • 3
  • 31
  • 61

2 Answers2

1

You can only do it certain ways which are shown below, also you can write a function and define your own way like I shown below. Hope this helps

colors = {
  green: {
    light: "lightgreen",
    dark: "darkgreen",
  },
  blue: {
    light: "lightblue",
    dark: "darkblue",
  }
}
// -- by defining your custom way
console.log(resolvePath(colors, "blue.light"));


function resolvePath (object, path) {
  return path
   .split('.')
   .reduce((o, p) => o ? o[p] : '', object)
 }
// -- by defining your custom way

// -- other ways below

console.log(colors["green"]["light"]);
console.log(colors.green.light);
console.log(colors["green"].light);
console.log(colors.green["light"]);
console.log(colors.green["light"]);
console.log(eval('colors.green.light')); // Thanks to @HaoWu comment, added this
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
A Paul
  • 8,113
  • 3
  • 31
  • 61
0

colors = {
  green: {
    light: "lightgreen",
    dark: "darkgreen",
  },
  blue: {
    light: "lightblue",
    dark: "darkblue",
  }
}

console.log(colors.green['light'])
Mohd Sabban
  • 182
  • 1
  • 12