2

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)
2

5 Answers 5

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

It’s not JSON even in your example. JSON is a text format.
You misunderstand; there is no JSON in the question or this answer.
2

you can simply do by this

let result = myarray.filter(x => x.members.find((a)=> a === "here put the string));

Comments

1

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))

Comments

0

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;
    }
  }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.