-1

I wonder if there's a more elegant, better one-liner to store all values of an iterator rather than a for loop:

// Create a test URLSearchParams object 
var searchParams = new URLSearchParams("key1=value1&key2=value2"); 

// Get all keys
let keys = [];
for(var key of searchParams.keys()) { 
    keys.push(key);
}
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • 1
    Using spread syntax should work `const keys = [...searchParam.keys()];` – Nick Parsons Feb 05 '20 at 09:27
  • This is likely a better question for https://codereview.stackexchange.com/ – Liam Feb 05 '20 at 09:28
  • 1
    `Array.from(iterator)` – VLAZ Feb 05 '20 at 09:28
  • `searchParams.keys()` already returns an array so. just use the returned array as `let keys = searchParams.keys()` – fubar Feb 05 '20 at 09:29
  • 2
    Does this answer your question? [Transforming a Javascript iterator into an array](https://stackoverflow.com/questions/28718641/transforming-a-javascript-iterator-into-an-array) – VLAZ Feb 05 '20 at 09:30
  • Well, that's unfortunate...voted for a dupe but there were two votes for "opinion based"...when we already have had this question. – VLAZ Feb 05 '20 at 09:31
  • 2
    @fubar "The keys() method of the URLSearchParams interface returns an iterator" https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/keys. – Slai Feb 05 '20 at 09:32
  • @T.J.Crowder I did get the [dupe auto-comment](https://stackoverflow.com/questions/60072674/storing-all-values-of-an-iterator?noredirect=1#comment106244544_60072674). However, since the ratio is 2:1 in votes, the close reason is now "opinion-based". – VLAZ Feb 05 '20 at 09:34

1 Answers1

0

You could use two different methods:

Spead Operator:

var searchParams = new URLSearchParams("key1=value1&key2=value2"); 
let keys1 = [ ... searchParams.keys() ];
console.log(keys1);
 

Array.from Spead Operator:

var searchParams = new URLSearchParams("key1=value1&key2=value2"); 
let keys2 = Array.from(searchParams.keys());
console.log(keys2);
 
Additional Reference
Menelaos
  • 23,508
  • 18
  • 90
  • 155