Then you can get the name directly based on the id
obj[id].name
In fact, the efficiency above is still relatively low.
Since the loop has been looped, just select the corresponding field directly from the loop
function getNameById(id) {
var name = '';
arr.forEach(function (v,i) {
if (v.id==id) {
name = v.name;
console.log(i);
return;
}
});
return name;
}
The difference between the above two methods is that if you keep getting the value repeatedly, choose the first method, because you only need to loop once, and there is no need to loop again later. The second method requires re-circulation every time you obtain it
I agree with what you said above, change the data structure. Change id to key. Turn other things into value. If you don’t need anything else, you can directly turn name into value
Suppose your original data looks like this:
Now you can convert the data format at one time to:
Then you can get the name directly based on the id
In fact, the efficiency above is still relatively low.
Since the loop has been looped, just select the corresponding field directly from the loop
The difference between the above two methods is that if you keep getting the value repeatedly, choose the first method, because you only need to loop once, and there is no need to loop again later.
The second method requires re-circulation every time you obtain it
I agree with what you said above, change the data structure. Change id to key. Turn other things into value. If you don’t need anything else, you can directly turn name into value