定位某一项值在多维数据中的位置
记录记录记录
/ * @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"]