基于二级数组键的Javascript数组过滤器

时间:2017-03-07 18:56:34

标签: javascript arrays

我正在尝试过滤具有2级孩子的数组。我能够过滤数组的第一级而不是第二级。我正在尝试返回email下具有特定collaborators的数组。这是结构

enter image description here

这是代码。此代码与email不匹配,因此返回数组中的所有项目

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

示例JSON:

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

必需的输出:

只有第一个有电子邮件test1@gmail.com

的数组

2 个答案:

答案 0 :(得分:1)

我不确定你想要的输出是什么,但希望以下示例可以帮助你。

希望这有帮助。

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

var email = "test1@gmail.com";
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>

答案 1 :(得分:0)

您希望filter回调返回布尔值,而不是数组。因此,请在合作者处使用someevery代替filter