我正在使用一个数组,我试图在其中找到嵌套 4 层深的对象的索引路径,并希望它以数组格式返回
[1, 0, 1, 0]
或字符串 1-1-1-1.
const field = {
id: "field-e656ba1c-2b18-4dfd-b582-03f1fbfc5642",
type: "field",
key: "testKey",
}
const layout = [
{
id: "section-766f11d4-c97c-4d5e-8dca-3bf5a2c0356e",
type: 'section',
children: [
{
id: "row-54eed1fd-0592-4196-bbff-e0befd65db41",
type: "row",
children: [
{
id: "column-4d9844ea-19c9-454f-b2f0-17a63f6d2f1e",
type: "column",
children: [{
id: "field-e656ba1c-2b18-4dfd-b582-03f1fbfc5642",
type: "field",
key: "testKeys",
}],
},
],
}
]
},
{
id: "section-766f11d4-c97c-4d5e-8dca-3bf5a2c0356e",
type: 'section',
children: [
{
id: "row-54eed1fd-0592-4196-bbff-e0befd65db41",
type: "row",
children: [
{
id: "column-4d9844ea-19c9-454f-b2f0-17a63f6d2f1e",
type: "column",
children: [field],
},
],
}
]
}
]
const findIdx = (array, fieldKey) => {
const find = (array) => {
if (!array) return
let inner,
index = array.findIndex((o) => {
if (o.key === fieldKey) return true
if (Array.isArray(o)) return (inner = find(o))
return (inner = find(o.children))
})
return index !== -1 && [index, ...(inner || [])]
}
return find(array)
}
console.log('path: ', findIdx(layout, 'testKey'))
然而,它每次都返回 false,并希望得到另一双眼睛来查看我哪里出错了。非常感谢任何帮助
您的代码永远无法访问
children
键。
这是
findIdx
的实现。由于您的 field.id
位于第一个 leaf,因此对于该示例,路径将是 [0,0,0,0]
:
function findIdx(array, fieldKey) {
for (let [idx, obj] of array.entries()) {
const res = obj.id === fieldKey ? [] : findIdx(obj.children ?? [], fieldKey);
if (res) return [idx, ...res];
}
}
const field = {id: "field-e656ba1c-2b18-4dfd-b582-03f1fbfc5642",type: "field",key: "testKey",}
const layout = [{id: "section-766f11d4-c97c-4d5e-8dca-3bf5a2c0356e",type: 'section',children: [{id: "row-54eed1fd-0592-4196-bbff-e0befd65db41",type: "row",children: [{id: "column-4d9844ea-19c9-454f-b2f0-17a63f6d2f1e",type: "column",children: [{id: "field-e656ba1c-2b18-4dfd-b582-03f1fbfc5642",type: "field",key: "testKeys",}],},],}]},{id: "section-766f11d4-c97c-4d5e-8dca-3bf5a2c0356e",type: 'section',children: [{id: "row-54eed1fd-0592-4196-bbff-e0befd65db41",type: "row",children: [{id: "column-4d9844ea-19c9-454f-b2f0-17a63f6d2f1e",type: "column",children: [field]}]}]}]
console.log(findIdx(layout, field.id));