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
Keith Michelson
3,395 PointsBuilding a dynamic object with inner objects in a loop
I'm reformatting an array of objects that i'm getting from an API endpoint into an object of objects with a key name. But I'm having trouble naming the first key and not just having it, 0, 1, etc...
I'm doing it like this:
var objects = {};
for (var i = 0; i < returnedObject.length; i++) {
objects[i] = {
time: returnedObject[i].time,
date: returnedObject[i].date
};
}
results I'm getting:
0: {
time: "6:00 PM",
date: "2015-10-30"
},
1: {
time: "6:00 PM",
date: "2015-10-30"
},
Any ideas on how to name objects[i]? like this below?
name1: {
time: "6:00 PM",
date: "2015-10-30"
},
name2: {
time: "6:00 PM",
date: "2015-10-30"
}
Thanks for any help.
Also, if anyone knows where to look for good tutorials on advanced object editing/creating please share.
2 Answers
Colin Marshall
32,861 PointsYou can do this:
var objects = {};
for (var i = 0; i < returnedObject.length; i++) {
var name = "name" + i.toString();
objects[name] = {
time: returnedObject[i].time,
date: returnedObject[i].date
};
}
Keith Michelson
3,395 PointsAhh, thank you Colin Marshall! I was able to take that and make it do exactly what I want and set the key name dynamically as well.
for (var i = 0; i < returnedObject.length; i++) {
var name = returnedObject[i].home_team;
objects[name] = {
time: returnedObject[i].time,
date: returnedObject[i].date
};
}