Home > Mobile >  How to access the data from an array of objects by TextInput in react native
How to access the data from an array of objects by TextInput in react native

Time:11-14

I have an array of objects in console. I want to get the id of the name that is entered in the TextInput by user. here is the result of: console.log("All teams", Teams); console.log("Selected team: ", myTeam);

All teams: Array [

Object { "__v": 0, "_id": "616e33b163d7ed23e95a9d98", "name": "test_team", },

Object { "__v": 0, "_id": "6181c5b3b5dfd98d4206e915", "name": "Team2", },

Object { "__v": 0, "_id": "6181c5d9b5dfd98d4206e919", "name": "team3", },

Object { "__v": 0, "_id": "6181c5e0b5dfd98d4206e91c", "name": "team4", },

Object { "__v": 0, "_id": "6181c5e4b5dfd98d4206e91f", "name": "team5", },

Object { "__v": 0, "_id": "6181c681b5dfd98d4206e924", "name": "team6", },

Object { "__v": 0, "_id": "618a046dbdb0ee4648b9da0f", "name": "sprinters", },

Object { "__v": 0, "_id": "618a058ebdb0ee4648b9da15", "name": "phone stepper", }, ]

Selected team: Team2

the value of Team2 is from user's entry, I need to get the value of this entry's "_id", something like " The id for this entry is: 6181c5b3b5dfd98d4206e915" How should I solve this problem? Thanks for your help in advance.

CodePudding user response:

You can run the find method on your array to pick out the first object with the name 'Team2', then access the _id property.

const id = allTeamsArr.find(obj => obj.name === 'Team2')['_id']

CodePudding user response:

Use Array.filter function to filter out.

var arr =[
    
     { "__v": 0, "_id": "616e33b163d7ed23e95a9d98", "name": "test_team" },
    
     { "__v": 0, "_id": "6181c5b3b5dfd98d4206e915", "name": "Team2" },
    
     { "__v": 0, "_id": "6181c5d9b5dfd98d4206e919", "name": "team3" },
    
     { "__v": 0, "_id": "6181c5e0b5dfd98d4206e91c", "name": "team4" },
    
     { "__v": 0, "_id": "6181c5e4b5dfd98d4206e91f", "name": "team5" },
    
     { "__v": 0, "_id": "6181c681b5dfd98d4206e924", "name": "team6" },
    
     { "__v": 0, "_id": "618a046dbdb0ee4648b9da0f", "name": "sprinters" },
    
     { "__v": 0, "_id": "618a058ebdb0ee4648b9da15", "name": "phone stepper" } ]
    
    var input = '6181c5b3b5dfd98d4206e915';
    var selected = arr.filter((item) => item._id == input)
  • Related