Object to pairs

JavaScript, Object, Array · Oct 22, 2020

Creates an array of key-value pair arrays from an object or other iterable.

const toPairs = obj =>
  obj[Symbol.iterator] instanceof Function && obj.entries instanceof Function
    ? Array.from(obj.entries())
    : Object.entries(obj);
toPairs({ a: 1, b: 2 }); // [['a', 1], ['b', 2]]
toPairs([2, 4, 8]); // [[0, 2], [1, 4], [2, 8]]
toPairs('shy'); // [['0', 's'], ['1', 'h'], ['2', 'y']]
toPairs(new Set(['a', 'b', 'c', 'a'])); // [['a', 'a'], ['b', 'b'], ['c', 'c']]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Object to pairs

    JavaScript, Object

    Creates an array of key-value pair arrays from an object.

  • Object to entries

    JavaScript, Object

    Creates an array of key-value pair arrays from an object.

  • Object from pairs

    JavaScript, Object

    Creates an object from the given key-value pairs.