0

I am trying to populate key value for picker element in react native from a kay, value pair. The app crashes when i try to pass the key-value list.

for example:(This does not work)

-- In the constructor
stateList: [{1:'Fortsworth'},{2:'Chicago'}],

--In the render()
this.state.stateList.map( (s, i) => {
  console.log('key='+i+',value='+s);
   return <Picker.Item key={i} value={s} label={s} />
});

However it only works if i pass array without key value pair. the below code works.

-- In the constructor
stateList: ['Fortsworth','Chicago'],

--In the render()
this.state.stateList.map( (s, i) => {
  console.log('key='+i+',value='+s);
   return <Picker.Item key={i} value={s} label={s} />
});

I need to pass the key as "1" and value as "Fortsworth" to the picker. Appreciate your inputs.

2
  • both snippets are currently identical... Commented Mar 12, 2017 at 19:01
  • sorry..mybad..updated the question now..the statelist where is doesn't work is a map where as its an array in the second example Commented Mar 12, 2017 at 19:27

2 Answers 2

1

This is the only way I know of to do this:

Object.keys(this.state.stateList).map(function(key) {
    let value = this.state.stateList[key];
    console.log('key=' + key + ',value=' + value);
    return <Picker.Item key={key} value={value} label={value} />
}

Essentially, you are looping over the list of keys and then pulling the value from your map using that key.

If anybody has a better solution, by all means provide it as an answer because I'm curious about this as well.

EDIT:

Sorry, just realized you have a list of map entries. For my answer, you would need stateList to be a map:

stateList: {1:'Fortsworth', 2:'Chicago'}

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.. Iterating over keys helped. "let value = this.state.stateList[key]" throwed "undefined is not an object error". I saved the list to another map object and retrieved the value from new map. That resolved the issue..
0

This should give you some idea -

var states = [{'1': 'Fortsworth'}, {'2': 'Chicago'}];
var key = '';

states.map(s => {
  key = Object.keys(s)[0];
  console.log("key",key,"value",s[key]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.