const user = [
{name:"jonh" ,id:EAD1234},
{name:"peter" ,id:EAD1235},
{name:"matt" ,id:EAD1236},
{name:"henry" ,id:EAD1237},
]
I have above mentioned array of object, I want to get selected user id dynamically based on user selection using es6 and javascript eg if i select john i should get EAD1234. and it must suitable on large number of records
I tried using filter method
No need to filter through the whole array if the id values are unique:
function getUserByID(id, users) {
for (const u of users) {
if (u.id === id) {
return u;
}
}
return null;
}
If your data really is exceptionally large and it makes sense to store it on the front-end look into using IndexedDB .
Edit : Someone in the comments somewhere mentioned Array.prototype.find() , so you might as well just use the built-in.
function getUserByID(id, users) {
return users.find((u) => u.id === id) || null;
}
If the data is samll,then just combine Array.filter()
and Array.map()
can do it.
If the data is too large,we can store the data into a database such as mysql
or redis
,then query it dynamiclly
const user = [ {name:"jonh",id:'EAD1234'}, {name:"peter",id:'EAD1235'}, {name:"matt",id:'EAD1236'}, {name:"henry",id:'EAD1237'} ] let id = 'EAD1234' let result = user.filter(u => u.id === id).map(u => u.name) console.log(result)
const user = [
{name:"john" ,id:'EAD1234'},
{name:"peter" ,id:'EAD1235'},
{name:"matt" ,id:'EAD1236'},
{name:"henry" ,id:'EAD1237'},
];
let userName = "john";
let userId = user.filter(user => user.name === userName)[0].name;
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.