Javascript 如何在 reactJS 中映射字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35191336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to map a dictionary in reactJS?
提问by nbroeking
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
我正在从在线 api 中获取一本字典,格式为 {{key: object}, {key: object},... For like 1000 Objects}。我想用 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?
此映射适用于数组,但显然不适用于字典。我怎样才能实现类似的目标?
采纳答案by garrettmaring
"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]);
}
回答by Przemys?aw Zalewski
If you target modern browsers or use some kind of transpiler you may use Object.entriesto 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. 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.
Object.entries
函数在 React 中非常方便,因为默认情况下没有对象/字典的简单迭代。React 要求您在迭代时为组件分配键以执行其差异算法。通过使用,Object.entries
您可以利用已键控的集合,而无需在数据中手动注入键或使用数组索引,这可能会导致在过滤、删除或添加项目后索引更改时出现意外行为。
Please see following example of Object.entries
usage with React:
请参阅以下Object.entries
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:
作为旁注,请记住,Object.entries
在使用数组解构时,映射结果时必须将数组参数括在括号中。以下代码会抛出语法错误:
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 tableunder 2017 features > Object static methods.
有关当前浏览器的支持,请参阅2017 功能 > 对象静态方法下的ECMAScript 兼容性表。
回答by rojoca
If you want to use map
as you usually would one option is 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;
});
回答by jmunsch
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