-2

I'm learning JavaScript on my own and am going through tutorials and cannot understand how to add the value of the second object to the first object. I tried to look at this How can I add a key/value pair to a JavaScript object? but I couldn't follow it. Below is the code I wrote:

 var person1 = {
      name: 'Joe',
  role: 'specialist'
};
var person2 = {
  name: 'Mr. Roberts',
  role: 'supervisor'
};

function addObjectProperty(obj1, key, obj2) {
  addObjectProperty(person1, 'manager', person2);

  return (person1.manager = (person2.name + person2.role));
}

console.log(person1.manager); 

My result returns:

undefined

But it should return:

//  --> { name: 'Mr. Roberts', role: 'supervisor' }

Could someone kindly advise me further? Thank you! :)

Community
  • 1
  • 1
  • 3
    The call to `addObjectProperty()` needs to be **outside** the function, not inside. – Pointy Feb 23 '17 at 21:50
  • @Pointy When I do your suggestion I get: **Mr. Roberts, supervisor** and not **{ name: 'Mr. Roberts', role: 'supervisor' }** . How would I fix this? I tried adding **obj1[key] = obj2** but it didn't change anything. Or would the way Ibrahim wrote the code below be the best way to go? Thank you so much! – learninghowtocode Feb 23 '17 at 22:28

1 Answers1

1

var person1 = {
  name: 'Joe',
  role: 'specialist'
};
var person2 = {
  name: 'Mr. Roberts',
  role: 'supervisor'
};

function addObjectProperty(obj1, key, obj2) {
  obj1[key] = obj2; // using bracket notaion to add obj2 as a property of obj1 under the key key
}

// call the function outside its definition or it'll cause an infinite recursion
addObjectProperty(person1, 'manager', person2); // person1.manager = person2

console.log(person1);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73