我有一个嵌套数组。我使用 array.filter
从父数组中获取子数组。
我的数据是这样的:
"accounts": [
{
"ID": "001yQdmAAE",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c25222423212962393f293e0c2d38233e622f2321" rel="noreferrer noopener nofollow">[email protected]</a>",
"users": [
{
"Name": "Inhome User",
"MobilePhone": "34877"
}
]
},
{
"ID": "00mAAE",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167f78386365736456776279643875797b" rel="noreferrer noopener nofollow">[email protected]</a>",
"users": [
{
"Name": "Inhome r",
"MobilePhone": "300077"
}
]
}]
我想根据 ID 从帐户数组中获取用户数组。我尝试了array.filter
。它返回
{ "ID": "001yQdmAAE",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abc2c5c3c4c6ce85ded8ced9ebcadfc4d985c8c4c6" rel="noreferrer noopener nofollow">[email protected]</a>",
"users": [
{
"Name": "Inhome User",
"MobilePhone": "34877"
}
}
我只想要用户数组
const res=this.state.data.filter((res)=>{
if(res.ID==record.ID){
return res.users;
}
});
console.log(res);
最佳答案
这并不完全是filter
作品。 filter
的回调函数应返回一个 bool 结果,该结果确定传入回调的元素是否应包含在 filter
的返回值中。执行过滤后,我们将 map
每个结果对象提取其 users
属性。
const /*this.state.*/data = {"accounts": [{"ID": "001yQdmAAE","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b12151314161e550e081e093b1a0f140955181416" rel="noreferrer noopener nofollow">[email protected]</a>","users": [{"Name": "Inhome User","MobilePhone": "34877"}]},{"ID": "00mAAE","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fdfabae1e7f1e6d4f5e0fbe6baf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>","users": [{"Name": "Inhome r","MobilePhone": "300077"}]}]};
const targetID = "00mAAE";
const result = data.accounts
.filter(e => e.ID === targetID)
.map(e => e.users);
console.log(result);
但是如果 ID
是唯一的,则使用 find
而不是 filter
,后者仅定位第一个匹配项:
const data = {"accounts": [{"ID": "001yQdmAAE","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb4b3b5b2b0b8f3a8aeb8af9dbca9b2aff3beb2b0" rel="noreferrer noopener nofollow">[email protected]</a>","users": [{"Name": "Inhome User","MobilePhone": "34877"}]},{"ID": "00mAAE","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a7374346f697f685a7b6e756834797577" rel="noreferrer noopener nofollow">[email protected]</a>","users": [{"Name": "Inhome r","MobilePhone": "300077"}]}]};
const targetID = "00mAAE";
const result = data.accounts.find(e => e.ID === targetID);
if (result) {
console.log(result.users);
}
关于javascript - array.filter 不返回 Reactjs 中父数组的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58005745/