DEV Community

Discussion on: Cool Object methods in JavaScript

Collapse
squigglybob profile image
squigglybob

Nice :0) I had heard of freeze recently. What would you do with the output of entries though?

P.s. typo in the last eg should be const ponyB = ponyA

Collapse
rawrasaurus profile image
Rawrasaurus

I was looking at this and thinking to myself like uh.. malfunction, malfunction.. how does this even work? :)

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)
Collapse
savagepixie profile image
SavagePixie Author • Edited on

Typo fixed! Thanks for the heads-up!

As for the output of entries, I think I shall refer to the others' replies :D

Collapse
avalander profile image
Avalander

What would you do with the output of entries though?

It's quite useful to convert objects to other formats, like query strings or SQL queries:

const query {
  page: 3,
  type: 'unicorn',
}

const toQueryString = query =>
  '?' + Object.entries(query)
    .map(([ key, value ]) => [ key, value ].join('=')) // Or .map(x => x.join('='))
    .join('&')

toQueryString(query) // '?page=3&type=unicorn'
Collapse
squigglybob profile image
squigglybob

Yep, that's nice. Object.keys(obj) always bothered me as then you needed to grab the value from the obj with the index of the key, but this way you have it there when you map etc.