0

I have this simple code below. I'm trying to query the name of any shape that is entered in the input box. I can pass the parameter in the function correctly, but when I try to query it using the parameter, it's causing me an error.

console.log(shape); //I'm getting the right input as parameter
console.log(shapes.shape.name); //not successful using passed parameter.

//code below

<div id="page">
   <input type="text" id="getShape"/>
   <input type="button" onClick="getShapeDetails()" />
</div>

<script>
   shapes = {
      "circle"   : {"name":"circle", "sides":"0", "color":"yellow"},        
      "triangle" : {"name":"triangle", "sides":"3", "color":"red"},         
      "square"   : {"name":"square", "sides":"4", "color":"blue"},  
   };

   function getShapeDetails(){
      var getShape = document.getElementById("getShape").value;

      function getShapesDetail(shape){
         console.log(shape);
     console.log(shapes.shape.name);
      }

      getShapesDetail(getShape);
   }
</script>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Prime
  • 3
  • 1
  • FYI, the code you posted has nothing to do with JSON. JSON is a *data exchange format*, like XML or CSV. In your example, `shapes` is imply a JavaScript object. – Felix Kling Apr 07 '13 at 16:50

2 Answers2

0

Try this:

console.log(shapes[shape].name);

You want to use shape as an index into the shapes structure.

Marcellus
  • 1,277
  • 8
  • 7
0

This works for me:

<html>
    <body>
        <script>
               var shapes = {
                    "circle"   : {"name":"circle", "sides":"0", "color":"yellow"},        
                    "triangle" : {"name":"triangle", "sides":"3", "color":"red"},         
                    "square"   : {"name":"square", "sides":"4", "color":"blue"},  
              };
                console.log("name: ", shapes.circle.color);
        </script>
    </body>

</html>
Gian Lorenzo Meocci
  • 1,136
  • 2
  • 14
  • 23