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"}.
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]; }.
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.
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/
Related
I have an array of objects, say memberToChange.checkboxes: ICheckbox[] like this:
Now, I have a variable, say internalNumber: string which has the value "3419". I want to get the object from the array of objects where the internalNumber matches the label property. Ultimately, I want to set the value attribute of that object to true.
My code is:
let checkboxes = _.find(scope.selectedMembers, (member: IMember) => member.member.uuid === memberId).checkboxes; //gives me array of checkboxes.
let checkboxToChange = _.find(memberToChange.checkboxes, function(checkbox: ICheckbox){
return (checkbox.label === internalNumber);
}); //gives me null, moreover, even a console.log inside the second find doesn't print. I'm thinking the two consecutive _.find statements are messing something up, not sure what.
For reference, this is my ICheckbox interface:
export interface ICheckbox {
label: string;
sublabel?: string;
value: boolean;
numberUuid: string;
}
I would expect that for internalNumber 3419, it should return me the second object from the array. But it returns undefined. I'm not sure what's going on here.
If there is a better way to find and set the value to true in one go only, I'd be happy to know that as well.
Any help is appreciated. Thank you.
Update:
After someone suggested using filter method of javascript, I tried this: (my scope is assigned to this)
scope.selectedMembers.filter(function(member) {
if (member.member.uuid === memberId) {
scope.memberCheckboxes = [];
console.log('found member'); //prints
scope.memberCheckboxes = member.checkboxes;
console.log(scope.memberCheckboxes); // print correctly, with checkboxes of the member
scope.memberCheckboxes.filter(function(checkbox) {
console.log('inside checkbox function'); //control doesnt even come here
if (checkbox.label === intNum) {
console.log('found checkbox'); // control doesnt come here
}
});
}
});
Here, I don't understand why the first console.log inside scope.memberCheckboxes.filter doesn't print? Am I missing something obvious here?
By some reason your memberToChange.checkboxes (or member.checkboxes in your updated question) have no elements.
It is the only explanation why it does not work since your code is otherwise correct. The fact that console.log('inside checkbox function') does not print confirms that.
Learning from Codecademy. I have to get property of an object to a variable( not property value). This is messing with my brain from an hour.
Here is the code (I messed up a bit to find solution. Please use comments understand it correctly. I am confused to ask)
SCREENSHOT: http://prntscr.com/bcj94x
var james = {
job: "programmer",
married: false
};
// set to the first property name of "james"
var aProperty = james["job"];
// print the value of the first property of "james"
// using the variable "aProperty"
console.log(james["job"]);
console.log(aProperty);
I am getting: this in the console when run the script
programmer
programmer
Thanks
What result did you expect?
Defining your object using with the Javascript Object Notation (JSON for short) results in an object with two properties job and married.
This object is referenced via the variable james. Everytime you are using james in your code, you are dealing with the referenced object.
The same goes for var aProperty = james["job"];. Everytime, when your variable aProperty is used, it refers to the job property of the object referenced with james.
It is like saying: »From now on, when I say "aProperty", I mean the job-property of james«.
Your comment is a bit misleading:
// set to the first property name of "james"
In this case job is the first property. Correct would be set to the property named job.
From the above should the result be not unexpected.
console.log(james["job"]);
console.log(aProperty);
Both print programmer because aProperty is equivalent to james["job"] like saying Thomas or the person who wrote this is referencing to me and thus equivalent.
If you want to get the key associated to a given value, you can do this:
var james = {
job: "programmer",
married: false
};
Object.prototype.getKey = function (value){
for(var property in this){
if(this.hasOwnProperty(property)) {
if(this[property] === value )
return property;
}
}
};
console.log(james.getKey('programmer'));
It will give you "job".
So, using this function, you can simply write:
var aProperty = james.getKey('programmer');
You can use a for in loop to put the key values of the key : value pairs found in your james object inside an array called aProperty, and then print out your results in the console.
var james = {
job: "programmer",
married: false
};
var aProperty = [];
for (myvar in obj) {
if (obj.hasOwnProperty(myvar)) {
aProperty.push(myvar);
}
}
console.log(aProperty[0]);
console.log(aProperty[1]);
I'm trying to sort out if this is plausible but have gotten syntax errors at best. So I am wondering if it is at all possible.
What I have is an object (example only)
var myObj = {
something1_max:50,
something1_enabled:false,
something1_locked:true,
something2_max:100,
something2_enabled:false,
something2_locked:true,
something3_max:10,
something3_enabled:true,
something3_locked:true
}
and what I want to do through a function is do something like again for example to sum things up..
function displayDetails(theScope, obj)
{
console.log(obj.[theScope]_max);
}
(function(){displayDetails('something3', myObj);})()
so when displayDetails() is called whatever the scope I can see in this example the max for that scope. In the console log for the example I would hope to see 10
Properties of JavaScript objects can always be accessed as a string using the bracket syntax, ie object['property']. This, of course, means you can build that string dynamically:
console.log(obj[theScope + '_max']);
Put the property name string in brackets.
console.log(obj[theScope + '_max']);
I know in javascript I can iterate over an object to get all of it's properties. If one or more of the properties is a method, is it possible to see what code is in the method instead of just the method name? E.g.
var a = someobject;
for (property in a) {
console.log(property);
}
Is it possible to get method code in a way similar to this? Thank you in advance.
You need to use toString, per the standard. i.e:
//EX:
var a = {method:function(x) { return x; }};
//gets the properties
for (x in a) {
console.log(a[x].toString());
}
You can also use toSource but it is NOT part of the standard.
PS: attempting to reliably iterate through an object with a for : loop is nontrivial and dangerous (for..in only iterates over [[Enumerable]] properties, for one), try to avoid such constructs. I would ask why, exactly, are you doing this?
Yes. It actually works. Try:
var a = {};
a.id = 'aaa';
a.fun = function(){alert('aaa');}
for (x in a) {
var current = a[x].toString();
if(current.indexOf('function') == 0){
current = current.substring(current.indexOf('{')+ 1, current.lastIndexOf('}'));
}
console.log(current);
}
But it will not work for browser native code.
You can use the toString method on the function
i.e.
function hello() {
var hi = "hello world";
alert(hi);
}
alert(hello.toString());
Update: The reason it wasn't working in JSFiddle was because I forgot to add the output inside of either console.log or alert - http://jsfiddle.net/pbojinov/mYqrY/
As long as a is an object, you should be able to use the square bracket notation and query a value from by argument with the same name as the objects property. For example:
a[ property ];
If you log typeof( property ), it will return "string" which is what we want.
i want to create a dynamic generated form using javascript, everything works fine, until i try to pass an array as parameter. When i do this, an error happens. Coulr anyone explain what this is?
Heres my code:
var loadFrm = function(component) {
for(nItem in component) {
var myComponent = "add" + firstToUpper(component[nItem].type);
var callComponent = myComponent + "(" + component[nItem].opt + ");";
eval(callComponent);
}
}
var json = [
{
type: "scale",
opt: {content: [{label: "male", value: "m"}, {label: "female", value: "f"}]}
}
];
loadFrm(json);
Edit Here's the error:
missing ] after element list
[Break on this error] addScale([object Object]);
If you use a debugger to look at the string callComponent, you'll probably find it looks something like this:
addScale([object Object])
...which isn't what you want. That's because you're effectively calling toString on your opt object, and the default toString on objects just looks like that. The eval error is because that's invalid syntax.
Generally speaking, any time you think you need to use eval, there's almost certainly a better answer. In this case, it looks like you're trying to call a function and pass in opt. Assuming these functions are "globals", you can do that like this:
var loadFrm = function(component) {
var nItem, functionName;
for (nItem = 0; nItem < component.length; ++nItem) {
functionName = "add" + firstToUpper(component[nItem].type);
window[functionName](component[nItem].opt);
}
}
Live example
Notes on the above:
Don't use for..in to loop through arrays unless you really know what you're doing. for..in does not enumerate the indexes of an array, it enumerates the properties of an object.
We look up the function by name using window[functionName]. This works because "globals" are actually properties of the window object, and you can look up properties using a string name for them using bracketed notation.
Having gotten the function via window[functionName], we just call it directly, passing in the object opt rather than a string form of it. I assume addScale expects to see an object.
I moved all of the vars to the top of the function because that's where they really are (details).
If you can, I'd recommend moving addScale and the related functions to their own object rather than putting them on window. The window namespace is already pretty crowded. Here's the live example modified to not add any symbols to window at all, instead putting the addScale function on an object called functions and using it from there.
Off-topic: The syntax var loadFrm = function(component) creates an anonymous function that it then assigns to a variable. This is used a lot, but unless you're creating different functions based on a condition, e.g.:
var f;
if (...) {
f = function() { ... };
}
else {
f = function() { ... };
}
...it's not actually useful. (If you are creating different functions based on a condition like that, then it's not only useful, it's necessary.) I recommend using named functions whenever possible, because a function with a name helps your tools help you by showing you the function name in error messages, call stacks, etc.
Off-topic 2: You have a variable called json, but FYI, it's not using JSON notation. It's using a combination of JavaScript array and object literal notation, which is a superset of JSON. You'll see a lot of people confused about this, I mention it because you said you're new and so it's worth nipping in the bud. :-) JSON is purely a notation. (A very useful one.)
Use this:
fn = eval(functionName);
fn(objParameter)