将项目过滤到数组内的数组中?

时间:2019-04-21 12:54:43

标签: javascript arrays ecmascript-6

const personData = {
  personList: [
    {

      personCodes: [
        {
          code: "001",
          desc: "Indian"
        }
      ]
    },
    
    {
     personCodes: [
        {
          code: "002",
          desc: "Spanish"
        }
      ]
    },
    {
      personCodes: [
        {
          code: "001",
          desc: "Spanish"
        },
        {
          code: "002",
          desc: "Spanish1"
        },
        {
          code: "003",
          desc: "Spanish2"
        }
      ]
    },
    
    {
      personCodes: [
        {
          code: "001",
          desc: "Russian"
        }
      ]
    },
    {
      personCodes: [
        {
          code: "001",
          desc: "Spanish"
        },
        {
          code: "002",
          desc: "Indian"
        },
        {
          code: "004",
          desc: "Japanina"
        }
      ]
    },
    {
      personCodes: [
        {
          code: "001",
          desc: "Spanish"
        },
        {
          code: "004",
          desc: "Indian"
        },
        {
          code: "003",
          desc: "Japanina"
        }
      ]
    },
    
  ]
};

const personID = ["001","003"];

const result = personData.personList.filter(role => role.personCodes && role.personCodes.find(group => personID.includes(group.code)));

console.log(result);

以下代码表示带有人员列表的人员数据。 每个人列表代表代码。 执行代码后,我将获得5种不同类型的数组,其中包含代码到personID数组中。 我希望像从人Data 3rd和6th对象中得到的那样。 有人可以调查一下并修改代码,我已经附上了所需的代码。 谢谢

2 个答案:

答案 0 :(得分:1)

您可以在x[5] = '\0'上使用every(),然后在其中使用personID

find()

答案 1 :(得分:0)

这里有另一个解决方案,基本上,您必须检查id中的每个元素personID中的{strong> 元素是否{strong}在object数组中的某个 personCodes中,属性code等于id

const personData = { personList: [ { personCodes: [ { code: "001", desc: "Indian" } ] }, { personCodes: [ { code: "002", desc: "Spanish" } ] }, { personCodes: [ { code: "001", desc: "Spanish" }, { code: "002", desc: "Spanish1" }, { code: "003", desc: "Spanish2" } ] }, { personCodes: [ { code: "001", desc: "Russian" } ] }, { personCodes: [ { code: "001", desc: "Spanish" }, { code: "002", desc: "Indian" }, { code: "004", desc: "Japanina" } ] }, { personCodes: [ { code: "001", desc: "Spanish" }, { code: "004", desc: "Indian" }, { code: "003", desc: "Japanina" } ] }, ] };
const personID = ["001", "003"];

const result = personData.personList.filter(role =>
{
    return Array.isArray(role.personCodes) &&
           personID.every(id => role.personCodes.some(p => p.code === id));
});

console.log(result);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}