javascript – How to map a dictionary in reactJS?

javascript – How to map a dictionary in reactJS?

If you target modern browsers or use some kind of transpiler you may use Object.entries to map [key, value] pairs within single iteration.

const obj = {
  foo: bar,
  baz: 42
}

console.log(Object.entries)
console.log(
  Object.entries(obj)
)

console.log(Mapping)
console.log(
  Object.entries(obj)
  .map( ([key, value]) => `My key is ${key} and my value is ${value}` )
)

Usage with React

Object.entries function is very handy with React as by default there is no easy iteration of objects/dictionaries. React requires you to assign keys to components when iterating in order to perform its diffing algorithm. By using Object.entries you can leverage already keyed collections without manually injecting keys in your data or using array indices, which can lead to undesired behavior when indices change after filtering, removing or adding items.

Please see following example of Object.entries usage with React:

const buttonCaptions = {
  close: Close,
  submit: Submit result,
  print: print,
}

const Example = () =>
  <div>
  {
    Object.entries(buttonCaptions)
    .map( ([key, value]) => <button key={key}>{value}</button> )
  }
  </div>

ReactDOM.render(<Example />, document.getElementById(react));
<div id=react></div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js></script>

Common syntax errors

As a side note, please keep in mind that when mapping result of the Object.entries you must wrap the array argument in parentheses when using array destructuring. Following code will throw syntax error:

console.log(
  Object.entries({key: value})
  .map([key, value] => `${key}: ${value}`)
)

Do this instead:

console.log(
  Object.entries({key: value})
  .map( ([key, value]) => `${key}: ${value}` )
)
    
console.log(
  Object.entries({key: value})
  .map(keyValuePair => `${keyValuePair[0]}: ${keyValuePair[1]}`)
)

Compatibility

For the current browser support please see the ECMAScript compatibility table under 2017 features > Object static methods.

Dictionaries in Javascript are called objects and you can iterate over them in a very similar way to arrays.

var dict = this.props.dict;

for (var key in dict) {
  // Do stuff. ex: console.log(dict[key])
}

If you were thinking of using map so that at the end of the iteration you had a complete array, then inside your for..in loop you could push to an array you declare earlier.

var dict = this.props.dict;
var arr = [];

for (var key in dict) {
  arr.push(dict[key]);
}

javascript – How to map a dictionary in reactJS?

If you want to use map as you usually would one option is Object.getOwnPropertyNames():

var newArr = Object.getOwnPropertyNames(this.props.dict).map(function(key) {
    var currentObj = this.props.dict[key];
    // do stuff...
    return val;
});

Leave a Reply

Your email address will not be published.