Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
brandonlind2
7,823 PointsAre there any methods that turn an object property name into a string?
so for example if I have a person object, can I call one of its properties in a variable and turn the property name into a string?
var person={
sam: {age:30,
job: 'accountant'},
alex: {age: 25,
job: 'store manager'}
}
var name= person.alex. possibleMethodImLookingFor();
1 Answer
Michael Hulet
47,913 PointsSo, to be clear, you're trying to take an Object and represent it as a String, right? You could try using JSON#stringify, like this:
var person = {sam: {age: 30, job: "accountant"}, alex: {age: 25, job: "store manager"}}
var alexString = JSON.stringify(person.alex);
//alexString will be '{"age":25,"job":"store manager"}'
If you want to turn it back into an Object, you could use JSON#parse, like this:
//Using alexString from the previous example
var alex = JSON.parse(alexString);
//alex will be {age: 25, job: "store manager"}