0

Heading Does anyone know how can I map a dictionary in 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>
    )
}

}

David Vittori
  • 1,146
  • 1
  • 13
  • 30

3 Answers3

3

You can map over the keys of an object using Object.keys.

return (
    <div>
        {
          Object.keys(this.state.dict).map(name => (
            <Services categories={this.state.dict[name]}></Services>
          ))
        }
    </div>
)
squgeim
  • 2,321
  • 1
  • 14
  • 21
1

For your data here is the solution to iterate it.

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);
            });
    }
}

Output:

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

reference: Iterate through object properties

Community
  • 1
  • 1
m.rohail.akram
  • 350
  • 1
  • 11
-1

You can also use Map syntax of EcmaScript6. From the Mozilla developer docs:

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
gualopezb
  • 334
  • 3
  • 10