1. 程式人生 > 實用技巧 >定位某一項值在多維資料中的位置

定位某一項值在多維資料中的位置

記錄記錄記錄

/ * @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"]