Reputation: 35
Here is my current code
var friendsObj = {};
var friends = ['John', 'Peter', 'Mary'];
friends.forEach(function(name, index) {
// implement your code below
console.log('Index '+ index + ' equals ' + name ) ;
});
console.log(friendsObj[0] === 'John');
// -> true
console.log(friendsObj[1] === 'Peter');
// -> true
console.log(friendsObj[2] === 'Mary');
// -> true
The results are this
Index 0 equals John Index 1 equals Peter Index 2 equals Mary false false false Randomized with seed 51872 Started F
Says that friendsObj should have "John", "Peter", and "Mary" as properties. I don't understand how it is not connecting back to friendsObj? Open to suggestions, thank you so much!
Upvotes: 1
Views: 44
Reputation: 89224
You need to set the property in the object for each index to be the element value.
var friendsObj = {};
var friends = ['John', 'Peter', 'Mary'];
friends.forEach(function(name, index) {
friendsObj[index] = name;
});
console.log(friendsObj);
console.log(friendsObj[0] === 'John');
console.log(friendsObj[1] === 'Peter');
console.log(friendsObj[2] === 'Mary');
This can be written more concisely by directly converting the array into a regular object with spread syntax.
let friends = ['John', 'Peter', 'Mary'];
let friendsObj = {...friends};
console.log(friendsObj);
Upvotes: 1