Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

js三层数组用value找出对应的key

怎么根据["110000", "110100", "110101"],找出对应的,北京,北京市,东城区

data = [
        {
            label:'北京',
            value:'110000',
            children:[{
                label:'北京市',
                value:'110100',
                children:[{
                     label:'东城区',
                     value:'110101'
                },{
                     label:'西城区',
                     value:'110102'
                }]
            }]
        }
        ...
        ...
        ...
    ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var data = [
        {
            label:'北京',
            value:'110000',
            children:[{
                label:'北京市',
                value:'110100',
                children:[{
                     label:'东城区',
                     value:'110101'
                },{
                     label:'西城区',
                     value:'110102'
                }]
            }]
        }
    ]

var partIds = ["110000", "110100", "110101"]; 

function find(list, level, partLabels) {
    var node = list.find(({ value }) => partIds[level] === value);

    if(node) {
        partLabels[level] = node.label;        
    }

    return node && node.children 
        ? find(node.children, ++level, partLabels) 
        : partLabels;
}

var result = find(data, 0, []);
console.log(result); // ["北京", "北京市", "东城区"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...