zoukankan      html  css  js  c++  java
  • 定位某一项值在多维数据中的位置

    记录记录记录

    / * @param needle 要查找的值 * @param haystack 被查找的数组 * @param property 当被查找项是对象时( 数组对象嵌套 )这个参数作为要查找的值的属性名称 ,如果是多维数组不会有任何影响 * @param children 当被查找项是对象时( 数组对象嵌套 )这个参数作为子集合属性名称 ,如果是多维数组不会有任何影响 * @return undefined | Object | * */


    
    


    let haystack = [
    {
    id: "first",
    type: "list",
    children: [
    {
    id: "second0",
    type: "list",
    children: [
    {
    id: "third0",
    type: "list"
    },
    {
    id: "third1",
    type: "list"
    }
    ]
    },
    {
    id: "second1",
    type: "list"
    }
    ]
    },
    {
    id: "first1",
    type: "list",
    children: [
    {
    id: "second2",
    type: "list"
    }
    ]
    }
    ];

    
    

    function array_search(
    haystack,
    needle,
    path = [],
    property = "id",
    children = "children"
    ) {
    if (
    haystack.some(item => {
    if (item[property] === needle) {
    path.push(item[property]);
    return true;
    } else if (item[children]) {
    path.push(item[property]);
    if (array_search(item[children], needle, path)) {
    return true;
    } else {
    path = [];
    return false;
    }
    } else {
    return false;
    }
    })
    ) {
    return path;
    } else {
    return null;
    }
    }

    
    

    let res = array_search(haystack, "third1");

    
    

    console.log(res); // ["first", "second0", "third1"]

     
  • 相关阅读:
    家庭养花秘笈1000问
    生活中来3000例·健康篇
    生命的奥秘百科(套装共10册)
    海军陆战队6:太空战舰
    历史文明探秘百科(套装共10册)
    中医养生知识读本
    上工养生话刮痧
    古法艾灸
    钻井液处理剂及其作用原理
    重金属污泥处理技术与管理
  • 原文地址:https://www.cnblogs.com/mr-shb/p/14173782.html
Copyright © 2011-2022 走看看