How to quickly find json data
As shown in the figure below, if the id is known, find the name value
世界只因有你2017-05-18 10:49:13
Suppose your original data looks like this:
var arr = [{
id:1,
name:'a'
},{
id:2,
name:'b'
}];
Now you can convert the data format at one time to:
var obj = {};
arr.forEach(function (v,i) {
obj[v.id] = v;
});
obj = {
1:{
id:1,
name:'a',
},
2:{
id:2,
name:'b'
}
};
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
ringa_lee2017-05-18 10:49:13
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
过去多啦不再A梦2017-05-18 10:49:13
fn(id) {
return arr.filter(o => o.id === id)[0].name; // id一定有对应值的情况
}