javascript object name inside a variable

Posted on 2014-07-10
Last Modified: 2014-07-11
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>
myNameofObject = 'Chris';

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


Open in new window

Question by:lvmllc
    1 Comment
    LVL 75

    Accepted Solution

    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
    // or just 

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Live - One-on-One JavaScript Help from Top Experts

    Solve your toughest problems, fast.
    JavaScript experts are online now and ready to help you.

    Suggested Solutions

    Title # Comments Views Activity
    Hide IE  and Firefox toolbar 5 34
    JavaScript - Chessboard 36 31
    c# string 6 26
    Create and populate iFrame onClick of a button? 1 20
    This article shows how to read a single webpage's HTML into a string variable, and it also shows how to automate a sequence so you can read and process a list of webpages.  I was tasked with reading and parsing a series of webpages to collect some s…
    Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now