React js中的字典

时间:2017-03-20 13:28:40

标签: javascript reactjs dictionary

Heading ##有谁知道如何在React js中映射字典?

export class ServiceFeatures extends React.Component {
    constructor(props) {
        super(props)
        this.state = {dict: {'awesome': ['wow','alo'], 'great': ['ano', 'alo' ]}}
    }

render() {
    return (
        <div>
            {this.state.dict.map((name, features) => (
              <Services categories={features}></Services>
          ))}
        </div>
    )
}

}

3 个答案:

答案 0 :(得分:3)

您可以使用Object.keys映射对象的键。

return (
    <div>
        {
          Object.keys(this.state.dict).map(name => (
            <Services categories={this.state.dict[name]}></Services>
          ))
        }
    </div>
)

答案 1 :(得分:1)

对于您的数据,这里是迭代它的解决方案。

var object= this.state.dict;

for (var property in object) {//properties in your dict
    if (object.hasOwnProperty(property)) {
    console.log("attr: "+ property); 
    object[property].map(function(item,index){ // iterate list items of each attribute
              console.log("list item : "+item);
            });
    }
}

输出:

attr: awesome
 list item : wow
 list item : alo
attr: great
 list item : ano
 list item : alo

参考:Iterate through object properties

答案 2 :(得分:-1)

您还可以使用EcmaScript6的Map语法。 来自Mozilla开发人员文档:

var myMap = new Map();
myMap.set(0, 'zero'); myMap.set(1, 'one'); 
for (var [key, value] of myMap) {
  console.log(key + ' = ' + value); 
} 
// 0 = zero
// 1 = one