So, out of curiosity, why are you assigning a value to i3 yourself? The point of for…in is that the value is set, by javascript, to each person in turn.
You have not actually stated what you are expecting your function to accomplish, but it seems as if you are trying to return a string representing the initials (first letter of the first name and first letter of the last name). Please state what you are expecting your function to do.
Also, what if the object had one million person entries? Are you really going to try and hard code all those if / else if statements? Think about the logic you would need to implement to create the initials from the first and last name.
EDIT: After reading your topic title again, I assume you are wanting to either modify the existing object so that each object in object has a new property with just the initials.
averaweb,
you have a typo in your function. after the for-in statement you open the bracket and immediately close it. so the for-in loop doesn’t do anything except assigning i3 to each property of ‘object’ ( “person1”, “person2”, “person3”). when it exits the loop ‘i3’ is assigned “person3”.
Then when it goes through the if-else statements, the only condition that it satisfies is the last one since ‘i3’ is now “person3”
so delete the closing bracket on the 3rd line of the function statement and add it above the console.log statement.
but just to reiterate what @RandellDawson pointed out, you don’t want to hard code each scenario. you want first and last initials to be the new property? then take advantage of the loop you already have.
try this instead:
object[i3].initial = object[i3].firstName[0] + object[i3].lastName[0]
in the for-in loop.