Create an array of key-value pair arrays from a given object

Trying to understand the code [k, obj[k], here object.keys is taking keys of an object and map them so ‘k’ refers to ‘a’ and ‘b’ which are keys. obj[k] seems we are putting mapped keys ‘k’ in an object ‘obj’ to make an array but how we are getting values in an array then?

You have misunderstood what obj[k] does.

Read this < https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation>

Are you asking how it is an array of arrays or why the array has the values it has?


You are not putting anything into the object, you are using the keys to access each property on the object.

map returns an array and here the callback is returning an array. So it becomes an array of arrays.


If you use Object.entries it might read a little better.

const object_to_pairs = (obj) =>
  Object.entries(obj).map(([key, value]) => [key, value]);

console.log(object_to_pairs({ a: 1, b: 2 })); // [ [ 'a', 1 ], [ 'b', 2 ] ]

ah thanks, this really helps

1 Like

thanks for such a detailed reply

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.