如何将具有属性“ a”的数组添加到具有attr的另一个数组中。 'b'基于具有attr的第三个数组的属性。 ['a','b']

时间:2019-05-13 08:11:33

标签: javascript arrays object ecmascript-6 lodash

我有3个数组,如下所示:

 Categories:

    0: {id: "123", name: "Cat 1"},
    1: {id: "456", name: "Cat 2"},
    2: {id: "789", name: "Cat 3"}


    Account Category:

    0: {categoryId: "123", supportId:"john@gmail.com" },
    1: {categoryId: "456", supportId:"john@gmail.com" },
    2: {categoryId: "789", supportId:"sherlock@gmail.com" },
    3: {categoryId: "123", supportId:"bikal@gmail.com"}


    Accounts:

    0: {email: "john@gmail.com", firstName: "john"},
    1: {email: "sherlock@gmail.com", firstName: "sherlock"},
    2: {email: "bikal@gmail.com", firstName: "bikal"}

我必须添加:

  • 将“类别”放入基于“类别”中“ id”的特定“帐户”
  • “帐户”中的“电子邮件”

链接它们的唯一方法是另一个具有两个字段的“帐户类别”数组。

我对如何做到这一点感到困惑。我可以使用lodash,但即使这样我也不确定如何执行此任务。

任何帮助将不胜感激,谢谢!

编辑: 输出应如下所示:

Accounts:

0: {categories:[{id: "456", name:"Cat 2"}, {id: "123", name: "Cat 1"}], email: "john@gmail.com", firstName: "john"},
1: {categories:[{id: "789", name:"Cat 3"}], email: "sherlock@gmail.com", firstName: "sherlock"},
2: {categories:[{id: "123", name:"Cat 1"}], email: "bikal@gmail.com", firstName: "bikal"}

1 个答案:

答案 0 :(得分:0)

非常简单-根据find正确supportId,然后取出categoryIdemail,然后返回所需的属性:

firstName
const Categories = [{id: "123", name: "Cat 1"},{id: "456", name: "Cat 2"},{id: "789", name: "Cat 3"}];
const AccountCategory = [{categoryId: "123", supportId:"john@gmail.com" },{categoryId: "456", supportId:"john@gmail.com" },{categoryId: "789", supportId:"sherlock@gmail.com" },{categoryId: "123", supportId:"bikal@gmail.com"}];
const Accounts = [{email: "john@gmail.com", firstName: "john"},{email: "sherlock@gmail.com", firstName: "sherlock"},{email: "bikal@gmail.com", firstName: "bikal"}];

const res = Categories.map(({ id, name }) => {
  const { supportId } = AccountCategory.find(({ categoryId }) => categoryId == id);
  const { email, firstName } = Accounts.find(({ email, firstName }) => email == supportId);
  return { id, name, email, firstName };
});

console.log(res);