Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a dictionary in reactJS?

I am getting a dictionary from an online api in the form of {{key: object}, {key: object},... For like 1000 Objects}. I would like to use reactJS to do something like

this.props.dict.map(function(object, key)){
 //Do stuff
}

This map works with arrays but it obviously doesn't work with dictionaries. How can I achieve something similar?

like image 876
nbroeking Avatar asked Feb 04 '16 02:02

nbroeking


People also ask

How do I map a dictionary in React JS?

Usage with React 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 it's diffing algorithm. By using Object.

How do you iterate through a dictionary in React?

Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.

How do I map a key value in React?

To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.

How do I map an array in React?

Given the code below, we use the map() function to take an array of numbers and double their values. We assign the new array returned by map() to the variable doubled and log it: const numbers = [1, 2, 3, 4, 5]; const doubled = numbers. map((number) => number * 2);console.


3 Answers

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 it's 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.

like image 108
Przemysław Zalewski Avatar answered Oct 19 '22 07:10

Przemysław Zalewski


"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]);
}
like image 21
garrettmaring Avatar answered Oct 19 '22 07:10

garrettmaring


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;
});
like image 5
rojoca Avatar answered Oct 19 '22 07:10

rojoca