[英]Javascript find() method not working for nested object/array/json values
I am trying to figure out why the nested find()
method is not working.我试图弄清楚为什么嵌套的
find()
方法不起作用。 Here is my data structure这是我的数据结构
const arr = [
{id: 1, name: "one"},
{id: 2, name: "two"},
{id: 3, name: "three"},
{id2: [
{id3: 30, name: "thirty"},
{id3: 50, name: "fifty"},
{id3: 70, name: "seventy"}
]
}
]
The idea is to access the id3
values for which I am using the nested find()
method like this:这个想法是访问我使用嵌套
find()
方法的id3
值,如下所示:
const ret = arr.find(function(el){
return el.id2.find(function(elps){
return elps
})
})
Interestingly, I am intermittently getting two different errors.有趣的是,我间歇性地遇到两个不同的错误。
TypeError: Cannot read property 'find' of undefined
OR I get或者我得到
find is not a function...
I also tried using some()
method for the second iteration but it returns the same errors.我也尝试使用
some()
方法进行第二次迭代,但它返回相同的错误。
If I use find()
on the parent level(1st iteration) array it works fine like this:如果我在父级(第一次迭代)数组上使用
find()
,它可以像这样正常工作:
const ret = arr.find(function(el){
return el.id > 2
})
My question: What is that I am missing in second iteration that the find()
method is not working there?我的问题:我在第二次迭代中缺少什么
find()
方法在那里不起作用?
You can use Array.isArray() before implementing the nested find()
to avoid using it on an undefined property or property where value isn't an array您可以在实现嵌套的
find()
) 之前使用 Array.isArray( ) 以避免在未定义的属性或 value 不是数组的属性上使用它
It's not really clear what your expected result is so the following returns the main array object that contains a matching sub-array element目前还不清楚您的预期结果是什么,因此以下返回包含匹配子数组元素的主数组 object
const arr = [ {id: 1, name: "one"}, {id: 2, name: "two"}, {id: 3, name: "three"}, {id2: [ {id3: 30, name: "thirty"}, {id3: 50, name: "fifty"}, {id3: 70, name: "seventy"} ] } ] const res = arr.find(({id2}) => Array.isArray(id2) && id2.find(({id3}) => id3 === 30)) console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.