通过传递数组中的函数中的查询来过滤记录

时间:2019-07-10 07:17:30

标签: javascript arrays function react-native object

我想通过将查询参数传递给JavaScript中的函数来获取记录。

const data = [{
    name: "ab",
    class: 1,
    grade: "A",
    teacher: {
      teacherName: "tab",
      age: 34,
      school: "ab pblc scl"
    }
  },
  {
    name: "cd",
    class: 2,
    grade: "B",
    teacher: {
      teacherName: "efg",
      age: 35,
      school: "cd pblc scl"
    }
  }
]

我的过滤器函数参数(第一个参数是数组,第二个是查询,可以是任何东西)

这些是一些测试条件。

filterMe(data,{name : "cd", class:"2",teacherName:"efg"})应该返回整个对象

{
   name: "cd",
   class: 2,
   grade: "B",
   teacher: {
      teacherName: "efg",
      age: 35,
      school: "cd pblc scl"
   }
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以使用Object.entries从提供的对象中获取每个键,并使用every检查每对键是否与过滤条件相同。如果该值是一个对象,则递归调用该函数:

const data = [{
    name: "ab",
    class: 1,
    grade: "A",
    teacher: {
      teacherName: "tab",
      age: 34,
      school: "ab pblc scl"
    }
  },
  {
    name: "cd",
    class: 2,
    grade: "B",
    teacher: {
      teacherName: "efg",
      age: 35,
      school: "cd pblc scl"
    }
  }
]

const advFilter = (d, f) => d.filter(o => nestedEvery(o, f))
const nestedEvery = (o, v) => Object.entries(v).every(([k,v]) => typeof v === 'object' ? nestedEvery(o[k], v) : o[k] === v)

const log = console.log
log(advFilter(data, { name: "cd", class: 2, teacher: { teacherName: 'efg' } })) // returns cd
log(advFilter(data, { name: "cd", class: 2, teacherName: 'efg' })) // returns []
log(advFilter(data, { name: "ab", class: 1, teacher: { teacherName: 'tab' } })) // returns ab

  

请注意,您不能简单地引用嵌套属性名称而不指定嵌套属性的名称,因为可能会有多个具有相同名称的属性。

答案 1 :(得分:-1)

我已经测试了一些测试用例,我认为我的代码可以正常工作。 试试看:

const data = [{
    name: "ab",
    class: 1,
    grade: "A",
    teacher: {
      teacherName: "tab",
      age: 34,
      school: "ab pblc scl"
    }
  },
  {
    name: "cd",
    class: 2,
    grade: "B",
    teacher: {
      teacherName: "efg",
      age: 35,
      school: "cd pblc scl"
    }
  }
]

function filterMe(data, query){
  result = data.filter( x => {
    return Object.keys(x).some( y => {
        
        if(y === "teacher"){
          return Object.keys(x[y]).some( u => {
            return Object.keys(query).some( q => {
                return query[q] === x[y][u]
            })
          })
        }else{
           return Object.keys(query).some( q => {
                return query[q] === x[y]
            })
        }
      })
    })

  console.log(result);
}

filterMe(data,{name : "cd", class:"2",teacherName:"efg"})