entries and fromEntries are awesome because they allows you to use Array.prototype.filter, map, reduce with objects (and their keys too!)
entries
fromEntries
Array.prototype.filter, map, reduce
Use them to mutate and create objects from existing objects.
For example:
import { resolve } from 'path' const paths = { home: './src/home/*', settings: './src/settings/*' } const resolvedPaths = Object.entries(paths) .reduce((acc, [key, value]) => { return { ...acc, [key]: resolve(__dirname, path) } }, {}) const normalisedPaths = Object.entries(paths) .reduce((acc, [key, value]) => { return { ...acc, [key]: value.replace('/*', '') } }, {}) const renamedPaths = Object.entries(paths) .reduce((acc, [key, value]) => { return { ...acc, [`${key}Path`]: value } }, {}) const pathsWithoutSettings = Object.entries(paths) .filter(([key]) => key !== 'settings') .reduce((acc, [key, value]) => { return { ...acc, [key]: value } }, {}) console.log(resolvedPaths.home) // C:/Users/jake/dev/my-project/src/home console.log(normalisedPaths.home) // ./src/home console.log(renamedPaths.homePath) // ./src/home/* console.log(Object.keys(pathsWithoutSettings)) // ['home']
and now thanks to fromEntries you can do the same without reduce:
reduce
const paths = { home: './src/home/*', settings: './src/settings/*' } const renamedPathEntries = Object.entries(paths) .map(([key, value]) => [`${key}Path`, value]) const renamedPaths = Object.fromEntries(renamedPathEntries)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
entries
andfromEntries
are awesome because they allows you to useArray.prototype.filter, map, reduce
with objects (and their keys too!)Use them to mutate and create objects from existing objects.
For example:
and now thanks to
fromEntries
you can do the same withoutreduce
: