skip to Main Content
const users = { user1: 18273, user2: 92833, user3: 90315 }

//Answer

const usersArray = Object.entries(users).map((keys, value)=> {return keys[0] + ' ' + value[1]});
console.log(usersArray);

//OUTPUT:

 ['user1 undefined', 'user2 undefined', 'user3 undefined']

I expect it to be like this:

 [ [ 'user1', 18273 ], [ 'user2', 92833 ], [ 'user3', 90315 ] ]

2

Answers


  1. this should work

    
    const users = { user1: 18273, user2: 92833, user3: 90315 }
    const usersArray = Object.entries(users).map((user) => ([user[0], user[1]]));
    console.log(usersArray);
    
    
    Login or Signup to reply.
  2. I agree with the example above, now the explanation.

    Undefined reason:

    The map function expects two arguments in the callback function: keys (the array of key-value pairs) and value (the index of the current element in the original array). In your code, you are using value as if it contained the user ID, but it actually refers to the second index of the keys array, which is always undefined.

    To fix this, access the user ID from index 1 of the keys array:

    const usersArray = Object.entries(users).map(keys => keys[0] + ' ' + keys[1]);
    

    now for the output format to be:

    [ [ 'user1, 18273' ], [ 'user2, 92833' ], [ 'user3, 90315' ] ]
    

    you simply set the return to []:

    const usersArray = Object.entries(users).map(keys => [keys[0] + ' ' + keys[1]]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search