DEV Community

Discussion on: Cool Object methods in JavaScript

Collapse
jakewhelan profile image
Jake Whelan • Edited on

entries and fromEntries are awesome because they allows you to use Array.prototype.filter, map, reduce with objects (and their keys too!)

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:

const paths = {
  home: './src/home/*',
  settings: './src/settings/*'
}

const renamedPathEntries = Object.entries(paths)
  .map(([key, value]) => [`${key}Path`, value])

const renamedPaths = Object.fromEntries(renamedPathEntries)