Reputation: 1227
I have an array like this:
const arr = [
{
groupname:'xyz',
members:[{
0: "alex",
1: "john"
}]
},
{
groupname:'abc',
members:[{
0: "khalifa",
1: "julia"
}]
}
];
I need to filter the members
array. For example, within the members array, I need to get only the entires with the julia
.
I tried like this but its showing empty array.
this.groups.filter(x => x.members === this.membername)
Upvotes: 2
Views: 1526
Reputation: 27
you can simply do by this
let result = myarray.filter(x => x.members.find((a)=> a === "here put the string));
Upvotes: 2
Reputation: 315
const arr = [
{
groupname:'xyz',
members:[{
0: "alex",
1: "john"
}]
},
{
groupname:'abc',
members:[{
0: "khalifa",
1: "julia"
}]
}
];
console.log(getEntity('julia'))
function getEntity(searchString) {
let result;
arr.forEach(val => {
val.members.forEach(val1 => {
Object.values(val1).forEach(val2 => {
if (val2 === searchString) {
result = val;
}
});
});
});
return result;
}
please try this
Upvotes: 0
Reputation: 222522
You can use Array.find() with the nested object. Also your JSON is not valid , kindly check the below example
let myarray = [
{
"groupname": "xyz",
"members": [
"alex",
"john"
]
},
{
"groupname": "abc",
"members": [
"khalifa",
"julia"
]
}
];
let result = myarray.filter(x => x.members.find((a)=> a === "julia"));
console.log(result);
Upvotes: 2
Reputation: 335
Here is one possible solution since members
is an array of objects but should be just an array...
const search = 'julia';
function filterArr(arr) {
for (const entry of arr) {
if (entry.members.every((elem) => Object.values(elem).includes(search))) {
return entry;
}
}
}
Upvotes: 0
Reputation: 35
You listed your members as array that containing an array.
Change your array to :
const arr = [
{groupname:'xyz', members:[ "alex", "john"]},
{groupname:'abc',members:["khalifa","julia"]}
];
and the logic function will be :
this.arr.filter(x => x.members.some((a)=> a === name))
Upvotes: 1