Ashik Basheer
Ashik Basheer

Reputation: 1601

Javascript array filter based on 2nd level array key

I am trying to filter an array that has 2 levels of children. I am able to filter the 1st level of the array but not the 2nd. I am trying to return an array that has a specific email under collaborators. Here is the structure

enter image description here

and here is the code. This code does not match email so return all the items in the array

this.firebase.list('/todo').
map(data => data.filter((e) => {
    return e.collaborators.filter((x) => {
        return x.email == email;
    });
}));

Sample JSON:

{
  "todo" : {
    "-Kee7m7WkNDhrbX_0Ycb" : {
      "collaborators" : [ {
        "email" : "[email protected]",
        "name" : "test"
      },
      {
        "email" : "[email protected]",
        "name" : "test1"
      } ],
      "created_at" : 1488913112569,
      "created_by" : "[email protected]",
      "preview" : "",
      "title" : "test",
      "updated_at" : 1488913112569
    },
    "-Kee7m7WkNDhrbX_0Ycb" : {
      "collaborators" : [ {
        "email" : "[email protected]",
        "name" : "test"
      },
      {
        "email" : "[email protected]",
        "name" : "test2"
      } ],
      "created_at" : 1488913112569,
      "created_by" : "[email protected]",
      "preview" : "",
      "title" : "test",
      "updated_at" : 1488913112569
    }
  }
}

Required output:

Only the first array which has an email [email protected]

Upvotes: 0

Views: 1084

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

I'm not sure what's your desired output but hope that the following example helps you.

Hope this helps.

var obj = {
  "todo" : {
    "-Kee7m7WkNDhrbX_0Yca" : {
      "collaborators" : [ {
        "email" : "[email protected]",
        "name" : "test"
      },
      {
        "email" : "[email protected]",
        "name" : "test1"
      } ],
      "created_at" : 1488913112569,
      "created_by" : "[email protected]",
      "preview" : "",
      "title" : "test",
      "updated_at" : 1488913112569
    },
    "-Kee7m7WkNDhrbX_0Ycb" : {
      "collaborators" : [ {
        "email" : "[email protected]",
        "name" : "test"
      },
      {
        "email" : "[email protected]",
        "name" : "test2"
      } ],
      "created_at" : 1488913112569,
      "created_by" : "[email protected]",
      "preview" : "",
      "title" : "test",
      "updated_at" : 1488913112569
    }
  }
};

var email = "[email protected]";
var result = [];

for(var key in obj["todo"]) {
   obj["todo"][key].collaborators.filter((x) => {
     if ( x.email == email )
       result.push( obj["todo"][key] );
  });
}

console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Bergi
Bergi

Reputation: 664185

You want the filter callback to return a boolean value, not an array. So use some or every instead of filter on the collaborators.

Upvotes: 0

Related Questions