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>
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. Commented Apr 7, 2013 at 16:50

2 Answers 2

0

Try this:

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

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

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

1 Comment

That answered my question. Thanks Marcellus.
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>

1 Comment

The OP does not use circle though, he uses shape which is a variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.