+ 3

Select object name that has a string as key?

x = { u: { “age”: 24 } } How do you select age? so that the output is 24

12th Oct 2021, 12:39 AM
Ginfio
Ginfio - avatar
9 Antworten
+ 1
You will always got data from server or API in this format and have to convert it to objects. This is how you can do it. https://www.w3schools.com/js/js_json_parse.asp
12th Oct 2021, 9:11 AM
PanicS
PanicS - avatar
+ 2
x['u']['age'] or x.u.age
12th Oct 2021, 12:41 AM
zexu knub
zexu knub - avatar
+ 1
zexu knub huh, i see. Can I ask you another question. It’s ok if you dont know. I found a localStorage data like this: x is the key. x: user: ‘{“loggedIn”: true, “accountType”: standard, “firstName”: “Joe”}’ — note the single quote. perhaps if i wanted to select “accountType” how would i do that?
12th Oct 2021, 12:59 AM
Ginfio
Ginfio - avatar
+ 1
zexu knub the difference between the new question i asked is that all the values and keys are stored as a string. everything inside user is wrapped as a string inside the ‘single’ quote. I’m wondering if it’s evn possible to get the values inside the single quote, because its being stored as like one string. user: ‘{“loggedIn”: true, “accountType”: standard, “firstName”: “Joe”}’
12th Oct 2021, 1:10 AM
Ginfio
Ginfio - avatar
+ 1
Again why don't you use ' sign. This whole syntax is wrong. Anyway idt you can actually do that cause then it will be a string. It isn't the most efficient solution but you can convert it to an array x.user.split(" ") & then you can access those values with their index.
12th Oct 2021, 1:19 AM
zexu knub
zexu knub - avatar
+ 1
Calviղ I made it that way on purpose. I found a code online where they had it age like that “age”. So i was trying ro figure out how you would select age when it’s inside quotes
13th Oct 2021, 2:10 PM
Ginfio
Ginfio - avatar
+ 1
Ginfio you still can select it using the usual object convention. Eg. x.u.age If the key string consists of invalid var symbol, for example var x = { u: { "my-age": 14 } } You can get my-age value by x.u["my-age"] https://code.sololearn.com/cz2lAnp0zGIG/?ref=app
13th Oct 2021, 4:12 PM
Calviղ
Calviղ - avatar
0
I just pasted your code you haven't used quotes for the age property. Either use ' or don't use anything.
12th Oct 2021, 1:01 AM
zexu knub
zexu knub - avatar
0
Ginfio your object is not in correct format, it should be var x = { u: { age: 24 } } https://code.sololearn.com/cglgeigepJFN/?ref=app
13th Oct 2021, 4:28 AM
Calviղ
Calviղ - avatar