array.filter 不返回 reactjs 中父数组的嵌套数组



我有一个嵌套数组。我正在使用array.filter从父数组中获取子数组。

我有这样的数据:

"accounts": [
{
"ID": "001yQdmAAE",
"email": "inhome.user@ator.com",
"users": [
{
"Name": "Inhome User",                    
"MobilePhone": "34877"
}
]
},
{
"ID": "00mAAE",
"email": "in.user@ator.com",
"users": [
{
"Name": "Inhome r",                    
"MobilePhone": "300077"
}
]
}]

我想根据 ID 从帐户数组中获取用户数组。我试过array.filter.它返回

{ "ID": "001yQdmAAE",
"email": "inhome.user@ator.com",
"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的回调函数应该返回一个布尔结果,该结果确定传递给回调的元素是否应包含在filter的返回值中。执行筛选后,我们将map每个结果对象以提取其users属性。

const /*this.state.*/data = {"accounts": [{"ID": "001yQdmAAE","email": "inhome.user@ator.com","users": [{"Name": "Inhome User","MobilePhone": "34877"}]},{"ID": "00mAAE","email": "in.user@ator.com","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);

但是如果IDs 是唯一的,则使用find而不是filter,它只定位第一个匹配项:

const data = {"accounts": [{"ID": "001yQdmAAE","email": "inhome.user@ator.com","users": [{"Name": "Inhome User","MobilePhone": "34877"}]},{"ID": "00mAAE","email": "in.user@ator.com","users": [{"Name": "Inhome r","MobilePhone": "300077"}]}]};
const targetID = "00mAAE";
const result = data.accounts.find(e => e.ID === targetID);
if (result) {
console.log(result.users);
}

您还需要使用map来返回正确的数据部分:

const res = this.state.data.filter(res => res.ID === record.ID).map(item = > item.users); // Add map here to get users array

过滤器返回 true 或 false,如果返回 false,则该元素将被过滤掉。

您应该首先过滤返回 true 或 false,然后使用 map 仅获取用户,然后使用 flat 将二维数组转换为普通数组。

const res=this.state.data.filter(
res=>
//return true or false in filter
res.AccountID==record.AccountID
).map(
//only need the users property
res=>res.users
).flat();//flatten [users] to users
console.log(res);

var data = {"accounts": [
{
"ID": "001yQdmAAE",
"email": "inhome.user@ator.com",
"users": [
{
"Name": "Inhome User",                    
"MobilePhone": "34877"
}
]
},
{
"ID": "00mAAE",
"email": "in.user@ator.com",
"users": [
{
"Name": "Inhome r",                    
"MobilePhone": "300077"
}
]
}]
}
function getUsers(){
var xx;
data.accounts.forEach(x => {
if(x.ID == "00mAAE"){
xx = x.users;
}
})
return xx;
};
console.log(getUsers());