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

     
  • 相关阅读:
    数据库相关(转)
    sql之left join、right join、inner join的区别
    PHP面试编程
    实验6 shell程序设计一(1)
    实验7 shell程序设计二(1)
    Linux软件安装管理
    Linux常用命令总结
    合唱团
    linux课后作业1
    linux网络服务实验
  • 原文地址:https://www.cnblogs.com/mr-shb/p/14173782.html
Copyright © 2011-2022 走看看