Referencing a variable when getting object value [duplicate] - javascript

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 9 years ago.
If I have a function like this:
var get = function(place, info){
return places.place.info;
}
and JSON like this:
var places = {
"london":{
"distance":50,
"time":100
}
}
How can I make the function get return the correct value if I use the following? At the moment it's taking it completely literally:
get("london", "time");

You should use square brackets notation:
var get = function(place, info){
return places[place][info];
};
I'd also add some fool proof check, e.g.:
var get = function(place, info){
return places[place] !== undefined
&& places[place][info];
};

Use square bracket syntax:
places[place][info]

Related

Javascript object oriented programming showing undefined [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 months ago.
I am new to javascript oop
i have been trying to get the desired value but it gives me undefined
class person {
constructor(isGreat, brain, personality) {
this.isGreat = isGreat;
this.brain = brain;
this.personality = personality;
}
getDetails(req) {
this.req = req;
let dic = {
isGreat: this.isGreat,
brain: `they have ${this.brain} brain`,
personality: `they have ${this.personality} personality`,
};
return dic.req;
}
}
let person0 = new person(true, "massive", "great");
console.log(person0.getDetails("isGreat"));
req can get read but dic.req shows undefined
The problem is console.log shows undefined.
dic doesn't have a req property. If you want to get a property whose name is stored in req variable, use the following syntax:
dic[req]
Just like accessing array members. In fact, a.b and a['b'] are equivalent in JavaScript.
BTW: The assignment this.req = req is not necessary.
You are returning the req property of your object, not the property with the key stored inside req. You need to use square brackets to get the index stored inside req.
return dic[req]
This is because it gets parsed as dic['isgreat'] rather than dic['req'].

Can't use a string in an object path [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 years ago.
I have this code :
success(JSON.parse(xhr.responseText).items[0].snippet.title);
The problem is I can access what I want with this but I'd like to be able to do this :
var path = 'items[0].snippet.title';
success(JSON.parse(xhr.responseText).path);
And it doesn't work :(
It's probably nothing but I can't figure out why.
Thanks!
For accessing object properties by string you need to use [ ] notation:
var foo = {bar : 2};
foo['bar']; // 2
But that won't work for nested properties, here is the approach I would follow using Array.reduce and ES6:
let path = 'items.snippet.title';
let response = JSON.parse(xhr.responseText);
let result = path.split('.').reduce((pre,cur) => {
return pre[cur];
}, response);
success(result);
In the first iterarion pre will be response, and cur 'items' returning result.items and so on, it won't work when accesing array indexes though so you will need to add some extra logic inside the reduce function.
const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/);
// filter foo[1] capturing foo and 1, then assign them using destructuring.
// Thanks for edit!
return ( Array.isArray(pre[cur]) ? pre[cur][position] : pre[cur]);

Pass an string representing an object function as callback [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
This code doesn't work:
var my = {
testFunction: function(text) {
alert(text);
}
};
var functionName = "my.testFunction";
var f = window[functionName];
f('yeha');
Any idea why?
Update:
I don't know in advance the functionName. It might be 'my.testFunction' or 'my.test.another.function' etc.
I'm writing a validation handler and all my js will know is a string representing a function that could be a function inside an object.
This should work.
var my = {
testFunction: function(text) {
alert(text);
}
};
// the string can't be evaluated as nested object hierarchy.
// split it to address the several nodes and properties
var functionName = "my.testFunction".split('.');
var f = window[functionName[0]][functionName[1]];
f('yeha');

using this keyword in object literal javascript [duplicate]

This question already has answers here:
Assigning the value of another key in javascript [duplicate]
(2 answers)
Closed 7 years ago.
According to me this is only being used if you need to call constructor like below
var dogObj = function(){
this.bark = "woof";
}
var dog1 = new dogObj();
console.log(dog1.bark);
Is there any cases where I use this on object literal?
var bark = {
this.bark = "dog"
}
Is above code valid? If yes,how do I call it?
you can use
var bark = {
bark : "dog"
}
and call it like
console.log(bark.bark)
this.bark = "woof";
Is not valid.
You have try something like below
var dog = {
bark : "dog"
}
And then you can access like console.log(dog.bark)
Once you formed any json string you can validate the sting using http://jsonlint.com/ just place your json string and the click on validate.

Define object by a variables string [duplicate]

This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Using a variable value to call an array element
(7 answers)
Closed 8 years ago.
Hard to explain.. I basicly want to do the following:
var doWhat = "speak";
var speak = {
hello: function() { alert: "Hello!"; }
};
// Won't work
doWhat.hello();
It's a bad example, but you should be able to get what I mean.
Is it possible somehow ?
You can use eval(doWhat).hello();. That way the contents of doWhat will be evaluated to the object reference.
You can do something like
var doWhat = {}, str = "speak";
doWhat[str] = {
hello : function() {}
};
doWhat[str].hello();
jsName = 'PageIndexController';
//ST1
eval("if( typeof jsName === 'undefined')alert(111);");
//ST1
eval("if( typeof " + jsName + " === 'undefined')alert(222);");
//ST1 not work
//ST2 work and the output: 222;
//there are two different way using eval, we will get 2 different outcome.

Categories

Resources