I have array of objects , and would like to fetch some attributes based on another one
assume
var lngs = [{id : 3 , label : 'a'} , {id : 2 , label : 'b' , {id : 4 , label : 'c'}];
now I need to get array of labels based on ids
for example
getAttrs([4,3]);
function getAttrs(ids , arr)
{
// as long as ids = [4,3] , it should return
["c","a"]
}
I tried this algorithm , but it did not work as expected
langsFromIds(ids)
{
var rslt = [];
var lngs = this.state.langs;
for (var i = 0 ; i < lngs.length ; i++)
{
if (lngs[i].id == ids[i])
{
rslt.push(lngs[i].label);
}
}
return rslt;
}
because it runs in this way (for example)
first iteration (i==0) => lngs[i].id == 3 && ids[i] == 4 (will not match)
second iteration (i==1) => lngs[i].id == 2 && ids[i] == 3 (will not match)
and so on ..
so it will return empty array
lngsobject is syntactically invalid. I have posted my answer assumingvar lngs = [{id : 3 , label : 'a'} , {id : 2 , label : 'b'} , {id : 4 , label : 'c'}];