skip to Main Content

I am busy with a javascript program where I have a function that runs through values and outputs only the certain values that I specified.

let printValuesOf = (jsObject, keys) => {
  for (let i = 0; i <= keys.length; i++) {
    let key = keys[i];
    console.log(jsObject[key]);
  }
}

let simpsonsCatchphrases = {
  lisa: 'BAAAAAART!',
  bart: 'Eat My Shorts!',
  marge: 'Mmm~mmmmm',
  homer: "d'oh!",
  maggie: "(Pacifier Suck)",
};

printValuesOf(simpsonsCatchphrases, 'lisa', 'bart', 'homer');

// Expected console output:

// BAAAAAART!
// Eat My Shorts!
// d'oh!

// Returns undefined

2

Answers


  1. you can modify the printValuesOf function to accept an array of keys instead of multiple arguments.

    Try this:

    let printValuesOf = (jsObject, keys) => {
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        console.log(jsObject[key]);
      }
    }
    
    let simpsonsCatchphrases = {
      lisa: 'BAAAAAART!',
      bart: 'Eat My Shorts!',
      marge: 'Mmm~mmmmm',
      homer: "d'oh!",
      maggie: "(Pacifier Suck)",
    };
    
    printValuesOf(simpsonsCatchphrases, ['lisa', 'bart', 'homer']);
    Login or Signup to reply.
  2. Take a look at this,

    // Looped to print out the field value
    let printValuesOf = (jsObject, keys) => {
      keys.forEach(key => {
        console.log(jsObject[key])
      })
    }
    
    // Sample data
    let simpsonsCatchphrases = {
      lisa: 'BAAAAAART!',
      bart: 'Eat My Shorts!',
      marge: 'Mmm~mmmmm',
      homer: "d'oh!",
      maggie: "(Pacifier Suck)",
    };
    
    // To get it all at once
    printValuesOf(simpsonsCatchphrases, ['lisa', 'bart', 'homer']);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search