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"]

     
  • 相关阅读:
    SpringBoot中mybatis配置自动转换驼峰标识没有生效
    mybatis-plus-扩展使用
    myabtis-plus使用
    mybatis-plus特性
    Mariadb Galera Cluster 故障快速拉起
    galera集群启动异常问题汇总
    Galera Cluster grastate.dat文件详解
    mongodb配置文件详解
    wsrep配置一览
    MySQL Galera cluster集群常用参数说明
  • 原文地址:https://www.cnblogs.com/mr-shb/p/14173782.html
Copyright © 2011-2022 走看看