David Vittori
David Vittori

Reputation: 1196

Dictionaries in React js

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

}

Upvotes: 0

Views: 18673

Answers (3)

m.rohail.akram
m.rohail.akram

Reputation: 350

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

Upvotes: 1

squgeim
squgeim

Reputation: 2351

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

Upvotes: 3

gualopezb
gualopezb

Reputation: 332

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

Upvotes: -1

Related Questions