Stack Exchange
Array of objects filter issue
I have got the following JSON as an array and I am trying to filter on roles attribute but I am not able to filter the results. Please help me.
var data = [{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}];

The JavaScript code which I wrote is below:
var results = data.filter(function(user) {
  var roles = user.roles;

  return roles.filter(function(role) {
    return role == 'clientsupervisor';
  });
});


That is invalid JSON, you need to escape your double-quotes (") or wrap your string in single-quotes ('). Note that JSON != JavaScript Object.

let's say i have two more keys at the same level of roles with names profileId and name. But in the result i need both of these keys name and profileId as id. How can we do it?

Your data variable has a syntax error. You need to remove the quotes that are wrapping it.
Also a little change in your filtering code.
Change from this: 
"[{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}]";

To this:
[{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}];

See it working:


var data = [{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"], "name": "Jack", "profileId": 34533}];

var results = data.filter(function (user){
 return user.roles.indexOf('clientsupervisor') > -1;
});

console.log(results);




let's say i have two more keys at the same level of roles with names profileId and name. But in the result i need both of these keys name and profileId as id. How can we do it?

@Venkat, the same code works for more keys in the same level. I updated my example to demonstrate this.

try this, simple way
var results = data.filter(function(user) {
    return user.roles.indexOf("clientsupervisor") > -1 ? true: false
});

and remove "" from data object, this is array object
var data = [{"roles":["citysupervisor"]},.....];


let's say i have two more keys at the same level of roles with names profileId and name. But in the result i need both of these keys name and profileId as id. How can we do it?
