i have array of thread objects this
threadlist:thread[]= [thread{id:1},thread{id:2},thread{id:3},...] i have threadrelation array inside user object below store if user has thread bookmarked or not. please note id in thread not match place in array.
user{ user_id:number,...(some other user typical properties) threadrelations:threadrelation[]=[ threadrelation{ id:2,//relates id property of thread object isbookmarked:true }, threadrelation{ id:18, isbookmarked:true },.. ]} i want create function returns array bookmarked threads of user. can achieve using 2 for-loops , if-statements, don't think efficient.. there methods can find specific object inside array directly?
updatebookmarkedlist(){ (var = 0; < this.activeuser.threadsrelation.length; i++){ if ( this.activeuser.threadsrelation[i].bookmarked == true){ var searchid = this.activeuser.threadsrelation[i].id; (var j = 0; j < this.threadlist.length; j++){ if (this.threadlist[j].id == searchid){ this.userbookmarkedlist.push(this.threadlist[j]) } } } } } thanks!
if thread.id unique identifier, should use map instead of array of objects no keys. without keys have iterate arrays no other choices.
when iterating array, try use built in iteration methods foreach. more efficient , looks neater loops.
to make supplement @tamas-hegedus's answer using es6 iterator feature, created jsfiddle using current version of javascript make "array-map", can replace map if thread.id not numeric.
see jsfiddle.
Comments
Post a Comment