1

I want to be able to quickly get the entry set from a map. But the entries function returns an iterator. That's not what I want. Sure, I could write a function to iterate through the entries and build it up into an entry set, but it would be much nicer to have my function say:

return map.entries();

instead of

return buildEntriesArray(map);

It doesn't seem like there's a clean way to code around the iterator problem other than wrap it in a bunch of decorated calls for the various inconsistent Iterator/entry set API cruft.

let a = [["foo.com", 32], ["bar.foo.com", 12]];
let m = new Map(a);
// add to map, etc.
let entries = Object.entries(Object.fromEntries(m.entries()));

How can I make it cleaner?

Garrett
  • 2,936
  • 1
  • 20
  • 22

1 Answers1

0
let entries = Array.from(m.entries());
Garrett
  • 2,936
  • 1
  • 20
  • 22
  • 2
    Could also `[...m.entries()]`. Also, if you're looking for clean, readable code, **always** use `const`, don't use `let` when possible - `let` warns readers that you *may be* reassigning the variable name. – CertainPerformance Apr 13 '20 at 05:35
  • `let` does not warn you that you may be reassigning the variable name. In fact, `let` declarations will result in error if there is already a binding on the lexical enviroment record. ``` var a = 1; let a = 2; // Error. ``` – Garrett Apr 13 '20 at 06:10
  • 1
    I'm talking about from the *code reader's* standpoint - anytime you use `let`, you are telling whoever is reading the code that you may be reassigning the variable. Interpreter warnings/errors have nothing to do with it. When you use `const` instead, the reader of the code has less cognitive overhead. The re-declarations you're thinking of are *not* the same thing as reassignment. Reassignment just requires the `=` assignment operator. – CertainPerformance Apr 13 '20 at 06:12
  • @Garrett you are confusing reassign and redeclate. Assigning a variable is just giving it a value `x = 1` reassigning is giving it a new value `x = 2`. That's it. `let` allows you to reassign values. Redeclaration is trying to create a new variable with the same name `let x; let x` is a redeclaration. – VLAZ Apr 13 '20 at 06:30