Reputation: 21
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
Reputation: 10384
4 errors in your code:
people.a
with people[a]
innerHTML()
with innerHTML
document.getElementById("p").innerHTML = print.name;
Code: http://jsfiddle.net/nabil_kadimi/vVSPG/
Upvotes: 0
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];
}
}
Also, I think you meant search("Hello")
, right? If not, then it would just be var search = function(x) { return people[x]; }
.
Upvotes: 3
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