Items function in JavaScript for looping over dictionaries like Python

23 February 2018   0 comments   Javascript, ReactJS

Too many times I've written code like this:

class MyComponent extends React.PureComponent {
  render() {
    return <ul>
      {Object.keys(this.props.someDictionary).map(key => {
        return <li key={key}><b>{key}:</b> {this.props.someDictionary[key]}</li> 
      })}
    </ul>
  }
}

The clunky thing about this is that you have to reference the dictionary twice. Makes it harder to refactor. In Python, you do this instead:

for key, value in some_dictionary.items():
    print(f'$key: $value')

To do the same in JavaScript make a function like this:

function items(dict, fn) {
  return Object.keys(dict).map((key, i) => {
    return fn(key, dict[key], i)
  })
}

Now you can use it "more like Python":

class MyComponent extends React.PureComponent {
  render() {
    return <ul>
      {items(this.props.someDictionary, (key, value) => {
        return <li key={key}><b>{key}:</b> {value}</li> 
      })}
    </ul>
  }
}

Example on CodeSandbox here

UPDATE

Thanks to @Osmose and @saltycrane for alerting me to Object.entries().

class MyComponent extends React.PureComponent {
  render() {
    return <ul>
      {Object.entries(this.props.someDictionary).map(([key, value]) => {
        return <li key={key}><b>{key}:</b> {value}</li> 
      })}
    </ul>
  }
}

Updated CodeSandbox here

Comments

Your email will never ever be published


Related posts

Previous:
Run something forever in bash until you want to stop it 13 February 2018
Next:
csso and django-pipeline 28 February 2018
Related by Keyword:
Fastest way to uniquify a list in Python >=3.6 23 December 2017
Be careful with using dict() to create a copy 09 September 2015
TfL Traffic cameras on a Google map 16 June 2010
GMapEZ - Google Maps API too complicated for you? 12 July 2006
Pleonasm 11 June 2006
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
Ever wondered how much $87 Billion is? 04 November 2003
Guake, not Yakuake or Yeahconsole 23 January 2010