Menu

gitpiper

toPairs javascript Code Snippet in 2024

objectarrayintermediate

Last Updated: 9 April 2024

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

  • Check if Symbol.iterator is defined and, if so, use Array.prototype.entries() to get an iterator for the given iterable.
  • Use Array.from() to convert the result to an array of key-value pair arrays.
  • If Symbol.iterator is not defined for obj, use Object.entries() instead.
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']]

javascript snippet similar to toPairs For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️