我有這個:
{ 'Payment' : {
'Referenced' : 'referenced payment',
'Conciliate' : 'conciliate payment',
'Multiple' : 'multiple payment'
}
}
但可以隨時更改隨機節點或添加更多節點,例如:
{ 'Payment' : {
'Referenced' : 'referenced payment',
'Conciliate' : 'conciliate payment',
'Multiple' : {
'mult1' : 'example1',
'mult2' : 'example1'
},
'Inventory' : {
'datastorage' : 'dt1'
}
}
所有節點都可以隨機分配,我需要按值搜索,可以通過:
referenced payment
并且需要:
Payment/Referenced
或者我發送:
example1
我需要:
Payment/Multiple/mult1
我不知道是否存在類似的東西。
uj5u.com熱心網友回復:
// Function
const findPath = (obj, query) => {
const makeArray = (obj, path = []) => {
const pairs = Object.entries(obj);
return pairs.map(([key, value]) =>
typeof value === "object"
? makeArray(value, [...path, key])
: { path: [...path, key], value }
);
};
return (
makeArray(obj)
.flat(Infinity)
.find(({ path, value }) => value === query)?.path.join("/") ?? null
);
};
// Usage
const path1 = findPath(
{
Payment: {
Referenced: "referenced payment",
Conciliate: "conciliate payment",
Multiple: {
mult1: "example1",
mult2: {
test: 123,
},
},
Inventory: {
datastorage: "dt1",
},
},
},
123
);
const path2 = findPath(
{
Payment: {
Referenced: "referenced payment",
Conciliate: "conciliate payment",
Multiple: {
mult1: "example1",
},
Inventory: {
datastorage: "dt1",
},
},
},
"referenced payment"
);
console.log("123: " path1);
console.log("referenced payment: " path2);
解釋
第一步是將物件轉換為物件樹及其路徑的線性陣列。這是遞回完成的。然后,將陣列展平以便通過 with 進行迭代Array.prototype.find,如果值與查詢匹配,則回傳路徑,如果未找到匹配項,則回傳null。
學分
感謝@Bravo 建議使用路徑陣列而不是模板文字
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/459679.html
標籤:javascript
上一篇:了解函式回傳和回呼
