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]);
Related
I'm having trouble figuring out how to customize console.log() so that it automatically prints out the label for each argument I pass into it. For example, I often do something like this, so that it's clear what each log is printing out:
console.log('firstName: ', firstName);
I would love to be able to simplify this to:
my.log(firstName);
Is there any way to pass the variable names of the caller args into console.log()? Or is there another way to do this? My wish is that I don't have to type out the variable name twice, just the once. And ideally print out multiple arguments each with its own label on its own line in the console. I'm aware that I can access the arguments list, but I don't know how to un-eval() each argument to get just its variable name, if that makes sense. I'm hoping it's something super-easy I missed.
Doing it the way you want is impossible (the log function doesn't know what name you called things.)
The way I work around this is to use the object shorthand {firstName}to create a temporary object.
You can then either use .log or .table to display it:
const firstName = 'bob';
console.log({firstName});
console.table({firstName});
// It also works for multiple variables:
const lastName = 'smith';
console.log({firstName, lastName});
You could use console.table() to print things in a more readable form:
(Look in the real console to see it.)
var obj = {
firstName: "name",
lastName: "smith"
};
function log(obj) {
console.table(obj);
}
log(obj);
Try this :
var my = {
log : function(name) {
console.log('firstName: ', name);
}
};
my.log("Rohit");
I am attempting to run a function in test environment (Mocha) and am running into an issue with calling my function when it is assigned to a variable (the test that is set up does the variable assignment). I'm sure this has been answered somewhere else, but every example I see is an asynchronous function, which this is not. The following code returns the object, but also undefined. I suspect that it is the "undefined" output that prevents my code from running in the test suite. Where is that undefined coming from, and is the correct output coming from the return statement or the console.log call?
var addTo = function(obj){
var object = {};
for(var i = 0; i<arguments.length; i++){
for(key in arguments[i]){
if(arguments[i].hasOwnProperty(key)){
object[key] = arguments[i][key];
}
}
}
return object;
}
var myObj = addTo({name: "John"}, {location: "space", age: 35});
console.log(myObj);
//returns:
//Object {name: "John", location: "space", age: 35}
//undefined
I know there is no real need to create an empty object here, as I could just add to the first object that is input into the function and start the for loop at i = 1. Just an attempt to fix the undefined issue (which is only what I think is the issue). If this is a duplicate, please link me to the correct post, as I cannot find it.
The console evaluates the expression and prints that. Since console.log doesn't return anything it displays undefined.
You forgot var in front of the 'key' variable. This is making it global.
I see you use semi-colons so add one after the } on line 11.
I am trying to access a certain member in a JavaScript object. In order to do this, I need to try out a couple of key values.
For example, Object['text/html'] which will give me an export link for a HTML document. However, not every object of this type will have a text/html key pair value.
In Python I would solve this problem using a Try-Catch block, with the KeyError exception. If I can do something similar in javascript, as in use an exception in a Try-Catch block, that would be great.
However, if alternatives exists instead of try catch blocks, that do achieve the same end goal, I would like to know about them as well.
EDIT:
I would prefer to use an exception over using functions. I do this because the text/html key might not be there, but it should be there. An exception seems more appropriate for this scenario
Javascript doesn't generate an exception when reading or writing a property that doesn't exist. When reading it, it just returns undefined. When writing it, it just creates the property.
You could create your own function that tests to see if the property exists and throws an exception if it does not (but you'd have to call that function whenever), but JS doesn't make an exception out of that on it's own like you are asking for.
If you want to test if a key exists on an object in javascript, you can use this construct with the in operator:
var obj = {};
var key = "test";
if (key in obj) {
// key exists
} else {
// key doesn't exist
}
If you try to read a key that doesn't exist, you will get undefined as the value.
var obj = {};
var value = obj.test;
alert(value === undefined);
The in operator does a better job of telling you whether the key exists that testing for undefined because undefined is a legal value for a key that exists.
In many cases, where you control the values that the keys have and a key that is present will never have a falsey value, you can also just check if the key has a truthy value:
var obj = {};
var obj.test = "hello";
if (obj.test) {
// key exists and has a truthy value
}
If you want to make sure that the object itself has the property and not any prototype that it is inheriting from, then you can do this:
var obj = {};
var obj.test = "hello";
if (obj.hasOwnProperty(test)) {
// key exists on the object itself (not only on the prototype)
}
Read this!
The accepted answer is correct however omits some points.
1) Accessing nested object
Like someone pointed out in the comment, Javascript returns undefined when the key doesn't exists in the object.
However, if you need to access an object inside an object (or an Array, or a function), well this break.
let a = {};
let userName = 'js'
let data = a.response[userName];
Cuz you will received actually a TypeError, basically because we are trying to read a property of undefined, which doesn't have any.
VM187:2 Uncaught TypeError: Cannot read properties of undefined (reading 'js')
at <anonymous>:2:22
2 Answering the question
The Python principle "Ask forgiveness not permission" - explain is actually for the most part working well in Javascript (and PHP, you didn't ask but well..). There are for sure some difference, or some situation where the difference is important, but for most use cases is the same
So this is how you would do it:
try {
let data = a.key1.key2['whatever'].nested.damn.object;
console.log(data)
} catch (error) {
let data = "noope";
console.log(data);
}
As you can see, in Javascript you don't really care about the error type, (for the most part, sure other situation you should case). Is almost like anything is in a Python's
try:
a = "hello" + 1 + {} + [] # crazy stuff here
except BaseException as bleh:
print(str(bleh))
Documentatin
MDN Working with objects
How do I check if an object has a key in JavaScript? [duplicate]
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/
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.