javascript 如何使用多个值作为引用从对象数组中获取多个对象?

fjaof16o  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(131)

我想知道如何创建一个函数,以某个参数为基础从对象数组中提取多个对象,例如:
输入:

const allContributors = [
   {
     index: 1,
     name: 'Contributor1',
     age: 20,
   }, {
     index: 2,
     name: 'Contributor2',
     age: 13,
   }, {
     index: 3,
     name: 'Contributor3',
     age: 24,
   },{
     index: 4,
     name: 'Contributor4',
     age: 34,
   },{
     index: 5,
     name: 'Contributor5',
     age: 43,
   },
]

不知何故,我需要根据他们在一周中的角色来安排一些贡献者。我想只使用索引值来建立以下输出

const contributorFiltered = [
       weekContributors: [
            Only Contributor with index 1, 3 and 4
          ],
           dayOne:[
              Contributor with index 1 and 3
            ]
     ]

最终输出:

const contributorFiltered = [
   weekContributors: [
           {
             name: Contributor1 ,
             age: 20,
           },
           {
             name: Contributor3 ,
             age: 24,
           },
           {
             name: Contributor4 ,
             age: 34,
           },
      ],
       dayOne:[
          {
            name: Contributor1 ,
            age: 20,
          },
          {
           name: Contributor3 ,
           age: 24,
          },
        ]
 ]
yhived7q

yhived7q1#

下面是创建函数的一种方法,该函数使用某个参数作为基础,从对象数组中提取多个对象:

const extractObjects = (allContributors, filter) => {
  const contributorFiltered = {
    weekContributors: [],
    dayOne: []
  };

  allContributors.forEach(contributor => {
    if (filter.weekContributors.indexOf(contributor.index) !== -1) {
      contributorFiltered.weekContributors.push({
        name: contributor.name,
        age: contributor.age
      });
    }
    if (filter.dayOne.indexOf(contributor.index) !== -1) {
      contributorFiltered.dayOne.push({
        name: contributor.name,
        age: contributor.age
      });
    }
  });
  return contributorFiltered;
};

然后,您可以按如下方式调用该函数:

const filter = {
  weekContributors: [1, 3, 4],
  dayOne: [1, 3]
}
const filteredResults = extractObjects(allContributors, filter);

注意,如果一个索引不存在于filter对象中,这个函数不会考虑这种情况,它会简单地忽略它。你也可以添加一个条件来处理它。

相关问题