javascript - How to quickly find json data
仅有的幸福
仅有的幸福 2017-05-18 10:47:13
0
3
797

How to quickly find json data
As shown in the figure below, if the id is known, find the name value

仅有的幸福
仅有的幸福

reply all(3)
世界只因有你

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

左手右手慢动作

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梦
fn(id) {
  return arr.filter(o => o.id === id)[0].name; // id一定有对应值的情况
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template