Home > front end >  How to iterate through two arrays and return key values to different object
How to iterate through two arrays and return key values to different object

Time:04-07

const phoneBook = {};
const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675']

function populate(names, numbers) {
  for(i = 0; i < populate.length; i  ) {
    phoneBook[names[i]] = numbers[i];
}
  
}

How can I get my for loop to iterate through both arrays simultaneously and return names as a key and numbers as the values?

CodePudding user response:

You mostly have the right idea.

Two suggestions:

  1. you want to use numbers.length or names.length as the number of iterations
  2. you probably don't want to mutate a global object

A working example would look something like this:

const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675'];

function populate(names, numbers) {
    const phoneBook = {};

    for(i = 0; i < names.length; i  ) {
        phoneBook[names[i]] = numbers[i];
    }

    return phoneBook;
}

const phoneBook = populate(names, numbers);

CodePudding user response:

More concisely, zip the arrays together, then pass that to Object.fromEntries(0

function makePhoneBook(names, numbers) {
  const entries = names.map((name, i) => [name, numbers[i]]);
  return Object.fromEntries(entries);
}

const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675']
const phoneBook = makePhoneBook(names, numbers);
console.log(phoneBook);

  • Related