Best approach to filter a Map to an Object in JS?
07:14 26 May 2024

I have a Map and I want to convert it to an Object filtering out entries that don't meet some condition.

My first solution was:

let m = new Map([
    ["key1", { flag: true}],
    ["key2", { flag: false}]
])

o = Object.fromEntries(m.entries()
    .filter(([k,v]) => v.flag)
    .map(([k,v]) => [k, true]));
console.log(o)

However it appears that iterator.filter is not generally available. So I came up with this alternative:

let m = new Map([
    ["key1", { flag: true}],
    ["key2", { flag: false}]
])

let o = Object.fromEntries(
    Array.from(m.entries())
    .map(([k,v]) => [k, v.flag])
    .filter(v => v[1]));

console.log(o)

Which I think is better supported.

Is there a better / faster solution? If iterator.filter was widely supported, would the first solution be a good solution?

javascript