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.
您可以在数组上运行 find 方法以挑选出名为“Team2”的第一个对象,然后访问_id
属性。
const id = allTeamsArr.find(obj => obj.name === 'Team2')['_id']
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)
You could try it by calling the below function on change event of Textinput:
<TextInput onChange={this.onChangeHandler} />
onChangeHandler = (e)=> {
const teamId = allTeams.filter(obj => obj.name === e.target.value)['_id']
console.log(e.target.value, teamId)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.