-1

Am stuck trying to add a function to add a new object to a const in javascript

const phonebook = {
  "Lily": {
    mobile: "+16235554420",
    work: "+12445552374",
    home: "+19775552223"
  },
  "Kyle, el hermano de Tim": {
    mobile: "+4235555616"
  }
};


function addPhoneNumber(name, numberType, number) {
  // write your code here
}
// when the function is ready, add the phone number of  xx
addPhoneNumber("Stephanie Noland", "mobile", "+4235555212");

console.log(phonebook["Stephanie Noland"].mobile); // "+4235555212"

I am aware that I can initiate a new object via

phonebook[name] = {}

But other than that I have trouble understanding how to add properties on that new object.

Normally a simple:

phonebook[name] = name,
phonebook[numberType] = numberType,
phonebook[number] = number

But that approach would only generate the following which is not what I need:

const phonebook = {
    mobile: "+16235554420",
    work: "+12445552374",
    home: "+19775552223"

As I need those to be under new objects with the name variable.

AegisNull
  • 33
  • 1
  • 5
  • 1
    You want to write into the new object so `phonebook[name][numberType] = number` – Nick Jun 16 '22 at 00:49
  • Does this answer your question? [How to create an object property from a variable value in JavaScript?](https://stackoverflow.com/questions/2241875/how-to-create-an-object-property-from-a-variable-value-in-javascript) – Nick Jun 16 '22 at 00:51

1 Answers1

1

Since it is objects inside objects, you can use [name][mobile] to access the mobile property of the corresponding name. When creating a new name, you have to use if-else conditions to first check if it exists. Note that [numberType] is used to create a dynamic key (where it creates a key with name as value of numberType).

const phonebook = {
  "Lily": {
    mobile: "+16235554420",
    work: "+12445552374",
    home: "+19775552223"
  },
  "Kyle, el hermano de Tim": {
    mobile: "+4235555616"
  }
};


function addPhoneNumber(name, numberType, number) {
  //if the name of person exists, then add the number to existing object
  if (phonebook[name]) {
    phonebook[name][numberType] = number;
  } 
  //else create a new object with the key as name of the person, and initialize it given number
  else {
    phonebook[name] = {
      [numberType]: number
    };
  }
}

// when the function is ready, add the phone number of  xx
addPhoneNumber("Stephanie Noland", "mobile", "+4235555212");

console.log(phonebook["Stephanie Noland"].mobile); // "+4235555212"
TechySharnav
  • 4,869
  • 2
  • 11
  • 29