user2620463
user2620463

Reputation: 21

Accessing nested objects in javascript

I am trying to run some JavaScript, but it is not working.

I have an object with two properties that are also objects.

var people = {
        me: {
            name: "Hello"
        },

        molly: {
            name: "Molly"
        }
    };

And I am trying to make a function that uses a for/in statement and an if statement to list the properties of people.

var search = function (x) {
        for (var a in people) {
            if (people.a.name === x) {
                return people.a;
            }
        }
    };

So the function loops through the properties of people and assigns them to the variable a. Therefore people.a will be equal to a property of people. Then the function returns the property (people.a).

So if I type in me as parameter x, will the function should return the properties for the me object? I put this code in jsLint and jsHint and it passed, but I decided to remove the corrections because they were useless.

I then want to print the object properties in the browser:

var print = search("me");
document.getElementById("p").innerHTML(print);

I have this linked to an html document, with a

tag id "p". I have tested javascript in the html document already, so I know that the javascript document is linked properly.

But the code will not work. Does anyone have any suggestions?

I have it working now thanks to the answers. But I thought that it would only print "Hello" to the screen, not { name: "Hello"}.

Upvotes: 2

Views: 107

Answers (3)

Nabil Kadimi
Nabil Kadimi

Reputation: 10384

4 errors in your code:

  • replace people.a with people[a]
  • replace innerHTML() with innerHTML
  • set HTML like this: document.getElementById("p").innerHTML = print.name;
  • As in a previous answer, search by name

Code: http://jsfiddle.net/nabil_kadimi/vVSPG/

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102743

You need to use people[a], not people.a. The former looks for a property with the name of the value stored in a; the latter looks for a property literally named "a", which of course doesn't exist.

for (var a in people) {
    if (people[a].name === x) {
        return people[a];
    }
}

Fiddle here.

Also, I think you meant search("Hello"), right? If not, then it would just be var search = function(x) { return people[x]; }.

Upvotes: 3

Lochemage
Lochemage

Reputation: 3974

people.a.name

you need to use the bracket operator if you want to access an item by name. Using people.a is literally searching for a member named 'a' instead of a member with the same name as the value of a.

Try:

people[a].name

instead.

Upvotes: 1

Related Questions