skip to Main Content

Consider the below object and I’m trying to console the below-mentioned output.

const jonas = {
  firstName: 'Jonas',
  lastName: 'Schmedtmann',
  age: 2037 - 1991,
  job: 'teacher',
  friends: ['Micheal', 'Peter', 'Steven']
};
console.log(`${jonas.firstName} has ${jonas.friends.length} friends, and his best friend is ${jonas.friends[0]}.`);

Now, instead of hardcoding friends in the console, how do I access the key name "friends" from the object?

3

Answers


  1. You can use Bracket Notation :

    const jonas = {
        firstName: 'Jonas',
        lastName: 'Schmedtmann',
        age: 2037 - 1991,
        job: 'teacher',
        friends: ['Micheal', 'Peter', 'Steven']
    };
    
    const keyName = 'friends';
    console.log(`${jonas.firstName} has ${jonas[keyName].length} ${keyName}, and his best ${keyName} is ${jonas[keyName][0]}.`);
    
    
    Login or Signup to reply.
  2. You can use the following element

    Object.keys(jonas) 
    

    that return an array of Keys of the object so you can take the value using

    Object.keys(jonas)[4]
    That return the key "friends"
    
    Login or Signup to reply.
  3. You could try a for loop:

    const jonas = {
      firstName: 'Jonas',
      lastName: 'Schmedtmann',
      age: 2037 - 1991,
      job: 'teacher',
      friends: ['Micheal', 'Peter', 'Steven']
    };
    
    let hasFriends = false;
    
    for (const key in jonas) {
    if (key === 'friends') {
      hasFriends = true;
      break;
      }
    }
    
    if (hasFriends) {
      console.log(`${jonas.firstName} has ${jonas.friends.length} friends, and his 
    best friend is ${jonas.friends[0]}.`);
    } else {
      console.log(`${jonas.firstName} does not have any friends.`);
    }
    

    or even try:

    for (const key in jonas) {
      console.log(`${key} has ${Array.isArray(jonas[key]) ? jonas[key].length : jonas[key]}.`);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search