在对象的嵌套数组中使用过滤器

时间:2018-09-06 17:16:48

标签: javascript arrays filter

我有这个对象数组,我正在尝试检索符合条件的学生,其中active为true且id或token不等于null。我得到的结果具有令牌== null。不知道我在做什么错。

IBAction

2 个答案:

答案 0 :(得分:0)

只需使用&&,当令牌和id不等于null时,它们将返回true。

var books = [{
        student: {
            studentInformation: [{
                active: true,
                id: "92839"
            }]
        }
    },
    {
        student: {
            studentInformation: [{
                active: true,
                token: null
            }]
        }
    },
    {
        student: {
            studentInformation: [{
                active: false,
                token: "eytqwedgd"
            }]
        }
    },
    {
        student: {
            studentInformation: [{
                active: true,
                id: null
            }]
        }
    }
]


let students = books.filter(stu =>
    (stu.student.studentInformation.every(y => (y.active = true && (y.id !== null && y.token !== null)))));
    
console.log(students);

答案 1 :(得分:0)

您可能想使用reduceforEach。在reduce回调内部,迭代studentInformation并检查条件,然后将其压入累加器数组

let books = [
  {
    student: {
      studentInformation: [
        {
          active: true,
          id: "92839"
        }
      ]
    }
  },
  {
    student: {
      studentInformation: [
        {
          active: true,
          token: null
        }
      ]
    }
  },
  {
    student: {
      studentInformation: [
        {
          active: false,
          token: "eytqwedgd"
        }
      ]
    }
  },
  {
    student: {
      studentInformation: [
        {
          active: true,
          id: null
        }
      ]
    }
  }
]
console.log(books)

let students = books.reduce(function(acc,curr){
   curr.student.studentInformation.forEach(function(item){
     if(item.active && item.token !==null && item.id !==null){
       acc.push(item)
     }
   }) 
return acc;

},[])
console.log(students)