如何使用javascript中的过滤器过滤基于性别的对象数组?

问题描述

下面是我试图过滤掉男性和女性数组的代码。但它似乎在男性和女性变量中再次返回整个数组。

  const male = await familyTree.filter(async(uncle) => {uncle.gender === 'Male'}); 

  const female = await familyTree.filter(async(aunt) => {aunt.gender === 'Female'});

我的对象数组:

var familyTree=  [
  {
    name: 'Ish',gender: 'Male',grandfather: 'null',grandmother: 'null',father: 'Shan',mother: 'Anga',wife: {}
  },{
    name: 'Vich',wife: {
      name: 'Lika',husband: 'Vich',fil: 'Shan',mil: 'Anga',children: [Array]
    }
  },{
    name: 'aras',wife: {
      name: 'Chitra',husband: 'aras',{
    name: 'Satya',gender: 'Female',husband: 'Vyan',children: [ [Object],[Object],[Object] ]
  }
]

当我在控制台中打印男性和女性时,它会再次返回整个数组而不过滤它们。可能是什么原因?

解决方法

如果您在箭头函数中使用 {},您需要return 从中获取结果。

我还删除了 async-await,如有必要,请重新引入。

const male = familyTree.filter((uncle) => {
    return uncle.gender === 'Male'
});

const female = familyTree.filter((aunt) => {
    return aunt.gender === 'Female'
});
,

对于 JavaScript 中的数组过滤,您可以使用一种简化的方式

interface FunctionInputs {
  firstFunction: {
    input: FirstFunctionInput,output: { data: number }
  },secondFunction: {
    input: SecondFunctionInput,output: { data: boolean }
  }
}

function callFirebaseFunction<K extends keyof FunctionInputs>(fn: K) {
  return function (input: FunctionInputs[K]['input']): Promise<FunctionInputs[K]['output']> {
    return firebase.functions().httpsCallable(fn)(input);
  };
};

callFirebaseFunction('firstFunction')({ x: 1 }).then(res => { /* { data: number } */ })
callFirebaseFunction('secondFunction')({ y: '1' }).then(res => {/* { data: boolean } */ })
,

使用花括号括起函数体{}时,需要使用return关键字返回值,

const male = familyTree.filter(uncle => {return uncle.gender === 'Male'});

或者如果您删除大括号:

const male = familyTree.filter(uncle => uncle.gender === 'Male')