Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 259
  • Last Modified:

javascript object name inside a variable

I am wondering if it is possible to store the name of an object in a var and then access it via the var
Ideally the following would put "blue" into the div.

<div id="myDiv">hi</div>
<script>
myNameofObject = 'Chris';

var myNameofObject = {age:50, eyeColor:"blue"};

document.getElementById("myDiv").innerHTML=Chris.eyeColor;
</script>

Open in new window

0
lvmllc
Asked:
lvmllc
1 Solution
 
Michel PlungjanIT ExpertCommented:
Not in the way you tried

myNameofObject = 'Chris'; // assign the string to a var called myNameofObject

var myNameofObject = {age:50, eyeColor:"blue"}; // hoist the variable - you should not use var later than when defining

The way to do this is
var myPeople = { 
  Chris: {age:50, eyeColor:"blue" },
  Joe: {age:45, eyeColor:"green" }
}

Open in new window


and then use
var name = "Chris"; // here is the var containing the name you want to look up

document.getElementById("myDiv").innerHTML=myPeople[name].eyeColor;

// or just 

document.getElementById("myDiv").innerHTML=myPeople["Chris"].eyeColor;

Open in new window

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now