Javascript object oriented programming showing undefined [duplicate] - javascript

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'].

Related

Unable to bind javascript variable to JSON object key [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 4 months ago.
I am trying to add a value in place of json object key but it always returns variable name.
My Code:
var projectName='';
let tempArray=[];
let output={};
for(i=0;i<myJsonArray.length;i++){
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output= {projectName :tempArray};
console.log(JSON.stringify(output));
This returns a JSON as
{"projectName":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
But I need something like this:
{"ABC":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
Can someone help on what I am missing here.
Kind Regards.
You should wrap the project name into [] that would help to make a value become a key
var name = '';
let tempArray = [];
let output = {};
for (i = 0; i < myJsonArray.length; i++) {
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output = {
[name]: tempArray
};
console.log(JSON.stringify(output));
P/s: I don't see any projectName variable there, so I replace it by name instead.

How to get object values with dynamic variable from json [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 3 years ago.
I want to get the value of an object field from JSON. I have a dynamic variable let check_permission_key = 'ratingscalename'; and have one JSON
let overwrite_key = {
studentimage: 'student',
ratingscalename: 'rating-scale-name',
ratingscale: 'rating-scale-name',
capturesettingset: 'capture-setting-set',
capturesetting: 'capture-setting-set',
eventlog: 'event-log',
goalcategorie: 'goal-category',
userimage: 'user',
datasheetlink: 'datasheet',
datasheetgoal: 'datasheet',
};
let get_value = overwrite_key.check_permission_key;
So I am fetching the data like this, but it is not working can anyone please help me to resolve this issue?
To access the object property value using a variable use Bracket ([]) notation:
let overwrite_key = {'studentimage':'student','ratingscalename':'rating-scale-name','ratingscale':'rating-scale-name','capturesettingset':'capture-setting-set','capturesetting':'capture-setting-set','eventlog':'event-log','goalcategorie':'goal-category','userimage':'user','datasheetlink':'datasheet','datasheetgoal':'datasheet'};
let check_permission_key = 'ratingscalename';
let get_value = overwrite_key[check_permission_key];
console.log(get_value);
Objects in javascript are pretty much arrays with String keys, so you can access a dynamic property like this:
let get_value = overwrite_key[check_permission_key];
You can use eval() function.
let overwrite_key = {
studentimage: 'student',
ratingscalename: 'rating-scale-name',
ratingscale: 'rating-scale-name',
capturesettingset: 'capture-setting-set',
capturesetting: 'capture-setting-set',
eventlog: 'event-log',
goalcategorie: 'goal-category',
userimage: 'user',
datasheetlink: 'datasheet',
datasheetgoal: 'datasheet',
};
let check_permission_key = 'ratingscalename';
let get_value = eval(`overwrite_key.${check_permission_key}`);
console.log(get_value);
JavaScript eval() Function

Not able to get JSON value dynamically [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 4 years ago.
I am working on the following snippet. Why am I not able to get the
let node = 'Em2';
console.log(data.node.c2);
work? As you can see I am able to get data while passing data.Em2.c1 but a dynamic format like this let node = 'Em2'; console.log(data.node.c2); I am getting this error
TypeError: Cannot read property 'c2' of undefined
Code:
var data ={
"Em1": { "c1":"#FFF", "c2":"#EEE" },
"Em2": { "c1":"#DDD", "c2":"#ooo" }
}
let node = 'Em2';
console.log(data.Em2.c1);
console.log(data.node.c2);
var data ={
"Em1": { "c1":"#FFF", "c2":"#EEE" },
"Em2": { "c1":"#DDD", "c2":"#ooo" }
}
let node = 'Em2';
console.log(data.Em2.c1);
console.log(data.node.c2);
Use square braces [] to access object member via variable
var data ={
"Em1": { "c1":"#FFF", "c2":"#EEE" },
"Em2": { "c1":"#DDD", "c2":"#ooo" }
}
let node = 'Em2';
console.log(data.Em2.c1);
console.log(data[node].c2);
Similar question: how to access object property using variable
Instead of console.log(data.node.c2), try console.log(data[node][c2])

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]);

Create a JSON field according to the value of a variable [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 6 years ago.
Supposing we have JSON data who came as :
msg = {
fieldName: fieldA
};
msg = {
fieldName: fieldB
};
I can receive multiple of this message, but everytime i have a different field, i want it to add in the 'data' json object, as i can access by using this :
data.fieldA
data.fieldB
By which way can i perform this ?
To access a property of an object when the name of the property is something your code figures out at runtime:
var propertyName = someCode();
var propertyValue = someObject[propertyName];
To create an object with an object initializer and a computed property name, you can do this in modern (ES2015) JavaScript:
var propertyName = someCode();
var someObject = {
[propertyName]: someValue
};
Prior to ES2015, you would do this:
var propertyName = someCode();
var someObject = {};
someObject[propertyName] = someValue;

Categories

Resources