简体   繁体   English

如何在reactJS中映射字典?

[英]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}. 我正在以{{key:object},{key:object}的形式从在线api获取字典,...对于类似1000对象}。 I would like to use reactJS to do something like 我想用reactJS来做类似的事情

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? 我怎样才能达到类似的效果?

"Dictionaries" in Javascript are called objects and you can iterate over them in a very similar way to arrays. Javascript中的“字典”称为对象,您可以以与数组非常相似的方式迭代它们。

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. 如果你正在考虑使用map,那么在迭代结束时你有一个完整的数组,然后在你的for..in循环中你可以推送到你之前声明的数组。

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

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

If you target modern browsers or use some kind of transpiler you may use Object.entries to map [key, value] pairs within single iteration. 如果您以现代浏览器为目标或使用某种类型的转换器,您可以使用Object.entries在单次迭代中映射[key, value]对。

 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 与React一起使用

Object.entries function is very handy with React as by default there is no easy iteration of objects/dictionaries. Object.entries函数非常方便React,因为默认情况下没有对象/字典的简单迭代。 React requires you to assign keys to components when iterating in order to perform it's diffing algorithm. React要求您在迭代时为组件分配键,以便执行它的diffing算法。 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. 通过使用Object.entries您可以利用已经键入的集合,而无需在数据中手动注入键或使用数组索引,这可能会在过滤,删除或添加项目后索引发生更改时导致意外行为。

Please see following example of Object.entries usage with React: 请参阅以下使用React的Object.entries用法示例:

 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. 作为旁注,请记住,在映射Object.entries结果时,必须在使用数组解构时将数组参数包装在括号中。 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. 有关当前浏览器支持,请参阅2017功能>对象静态方法下的ECMAScript兼容性表

If you want to use map as you usually would one option is Object.getOwnPropertyNames() : 如果你想像Object.getOwnPropertyNames()一样使用map ,那么一个选项就是Object.getOwnPropertyNames()

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

Assuming you meant: {key: object, key2: object} 假设你的意思是: {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): 你可以做类似的事情(不确定与getOwnPropertyNames的确切差异,但它应该做同样可能性能较差):

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

Edit: 编辑:

If you only want the enumerables of the object use Object.keys 如果您只想要对象的可枚举使用Object.keys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM