How to map a dictionary in reactJS?

前端 未结 4 537
暖寄归人
暖寄归人 2020-12-31 04:08

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

相关标签:
4条回答
  • 2020-12-31 04:51

    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;
    });
    
    0 讨论(0)
  • 2020-12-31 04:58

    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.

    0 讨论(0)
  • 2020-12-31 05:03

    Assuming you meant: {key: object, key2: object}

    You could do something like(not sure the exact differences to getOwnPropertyNames but it should do about same maybe less performant):

    Object.keys(this.props.dict)
        .map(function(key)){ 
             var object = this.props.dict[key]
             //Do stuff
         })
    

    Edit:

    • Object.getOwnPropertyNames vs Object.keys

    If you only want the enumerables of the object use Object.keys

    0 讨论(0)
  • 2020-12-31 05:13

    "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]);
    }
    
    0 讨论(0)
提交回复
热议问题