如何在仅具有 "child" 数组的一个已识别属性的数组中查找对象的 ID
How to find the id of an object within an array having only one identified attribute of the "child" array
我想帮助开发一个函数,使用 Javascript 中最优化的方法来查找只有“子”对象代码(在 dataArray 中)的“父”对象的 ID。
示例:
getIdParent("240#code") -> return "1"
[
{
id: 0,
dataArray:[
{
id: 182,
code: "182#code",
name: "Product1"
},
{
id: 183,
code: "183#code",
name: "Product2"
}
]
},
{
id: 1,
dataArray:[
{
id: 240,
code: "240#code",
name: "Product2"
},
{
id: 341,
code: "341#code",
name: "Product2"
}
]
}
]
提前致谢。
这里你真的没有太多选择。
我能想到的唯一真正的优化是基于您期望调用此函数的频率。
如果只有一次,你只需要遍历数组,尽早搜索值和return以防止不必要的迭代。
function getIdParent(childCode) {
return arr.find(parent =>
parent.dataArray.some(({ code }) => code === childCode))?.id
}
如果多次,你应该建立一个子对象code
到父对象的索引映射,然后引用那个
const arr = [{"id":0,"dataArray":[{"id":182,"code":"182#code","name":"Product1"},{"id":183,"code":"183#code","name":"Product2"}]},{"id":1,"dataArray":[{"id":240,"code":"240#code","name":"Product2"},{"id":341,"code":"341#code","name":"Product2"}]}]
const codeMap = arr.reduceRight((map, parent) => {
parent.dataArray.forEach(({ code }) => {
map.set(code, parent)
})
return map
}, new Map())
function getIdParent(code) {
return codeMap.get(code)?.id
}
let search = ["240#code", "182#code", "NotFound"]
search.forEach(code => {
console.log("Parent ID for", code, "=", getIdParent(code))
})
我想帮助开发一个函数,使用 Javascript 中最优化的方法来查找只有“子”对象代码(在 dataArray 中)的“父”对象的 ID。
示例: getIdParent("240#code") -> return "1"
[
{
id: 0,
dataArray:[
{
id: 182,
code: "182#code",
name: "Product1"
},
{
id: 183,
code: "183#code",
name: "Product2"
}
]
},
{
id: 1,
dataArray:[
{
id: 240,
code: "240#code",
name: "Product2"
},
{
id: 341,
code: "341#code",
name: "Product2"
}
]
}
]
提前致谢。
这里你真的没有太多选择。
我能想到的唯一真正的优化是基于您期望调用此函数的频率。
如果只有一次,你只需要遍历数组,尽早搜索值和return以防止不必要的迭代。
function getIdParent(childCode) {
return arr.find(parent =>
parent.dataArray.some(({ code }) => code === childCode))?.id
}
如果多次,你应该建立一个子对象code
到父对象的索引映射,然后引用那个
const arr = [{"id":0,"dataArray":[{"id":182,"code":"182#code","name":"Product1"},{"id":183,"code":"183#code","name":"Product2"}]},{"id":1,"dataArray":[{"id":240,"code":"240#code","name":"Product2"},{"id":341,"code":"341#code","name":"Product2"}]}]
const codeMap = arr.reduceRight((map, parent) => {
parent.dataArray.forEach(({ code }) => {
map.set(code, parent)
})
return map
}, new Map())
function getIdParent(code) {
return codeMap.get(code)?.id
}
let search = ["240#code", "182#code", "NotFound"]
search.forEach(code => {
console.log("Parent ID for", code, "=", getIdParent(code))
})