Problem with adding extra property to object

Hello guys,

I would very much appreciate a little help with this code.

var object = {
    person1: {
        firstName:'Irakli',
        lastName: 'Ghachava',
        age: 25,
        address: 'Tbilsi, Noneshvili Street'
    },
    person2: {
        firstName: 'Zuri',
        lastName: 'Ghachava',
        age: 29,
        address: 'Tbilisi, Guramishvili Street'
    },
    person3: {
        firstName: 'Toni',
        lastName: 'Montana',
        age: 45,
        address: 'Florida, Miami'
    }
}


function initials(){
 for (var i3 = 0 in object){
 } 
 if (object[i3].firstName == 'Irakli'){
 object[i3].initial = 'IG'
 } else if (object[i3].firstName == 'Zuri'){
     object[i3].initial = 'ZG'
 } else if (object[i3].firstName == 'Toni'){
     object[i3].initial = 'TM'
 }
 console.log(object)
}

When I console.log object it pushes only ‘TM’ and the other two are left the same. What am I missing? What should I change in the code?

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.

{
  person1: {
    firstName: 'Irakli',
    lastName: 'Ghachava',
    age: 25,
    address: 'Tbilsi, Noneshvili Street'
  },
  person2: {
    firstName: 'Zuri',
    lastName: 'Ghachava',
    age: 29,
    address: 'Tbilisi, Guramishvili Street'
  },
  person3: {
    firstName: 'Toni',
    lastName: 'Montana',
    age: 45,
    address: 'Florida, Miami',
    initial: 'TM'
  }
}

this is the output when you call the function
i want to add initials to all three objects but it has added ‘TM’ to just last one

Anybody??? I would appreciate a little help

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 @camperextraordinaire 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.

1 Like