Array.flat/flatMap and Object.fromEntries

Array.flat and Array.flatMap

The documentation says:

const numbers = [[1, 2, 3], [4, 5, 6], [7, [8, 9]]];
numbers.flat(); // [1, 2, 3, 4, 5, 6, 7, [8, 9]];
numbers.flat(1); // [1, 2, 3, 4, 5, 6, 7, [8, 9]]; (same as above)
numbers.flat(2); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
const words = ["it's always", "sunny in", "philadelphia"];
words.reduce((a, w) => a.concat(w.split(" ")), []); // ["it's", "always", "sunny", "in", "philadelphia"]
const words = ["it's always", "sunny in", "philadelphia"];
words.map(x => x.split(' ')).flat(1); // ["it's", "always", "sunny", "in", "philadelphia"]
const words = ["it's always", "sunny in", "philadelphia"];
words.flatMap(x => x.split(' ')); // ["it's", "always", "sunny", "in", "philadelphia"]

Object.fromEntries

To understand Object.fromEntries, let’s first look at Object.entries. This is a convenient way to convert and array to an object, something that is done all the time.

{
"1": {
"id": 1,
"name": "Joe"
},
"2": {
"id": 2,
"name": "Mary"
}
}
Object.entries(payload);
[
["1", { id: 1, name: "Joe" }],
["2", { id: 2, name: "Mary" }]
];
const array = [
[1, { id: 1, name: "John" }],
[2, { id: 2, name: "Mary" }]
];
const users = Object.fromEntries(array);
// {"1": { id: 1, name: "John" }, "2": { id: 2, name: "Mary" }}
array.reduce((acc, v) => {
acc[v[0]] = v[1];
return acc;
}, {});

--

--

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store