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

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

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.

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

How to set a String as a key for an object? [duplicate]

This question already has answers here:
JavaScript set object key by variable
(8 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 2 years ago.
Given
this.state = {email: "something", firstName: "something" }
const name = "email"
const value = this.state[name]
I want to make a new object like this
{email: "something"}
basically without the other stuff
I tried
const new = {name: value}
This makes it {name: "something"} I want {email: "something"}
but the key doesn't attach to a variable and I want email to not be known to me
You've got two problems with your code. new is a reserved word, so you can't make a variable named new. And second, what you're looking to do is something like this:
const name = 'email';
const myObj = {
[name]: 'something'
};
Please use [] while providing key as a variable
var name = "email"
var value = "something"
{[name]: value}
=> {email: "something"}

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

Categories

Resources