使用FP减少对象数组中对象的对象

时间:2018-02-21 11:17:28

标签: javascript arrays functional-programming higher-order-functions

我从API获得以下数据:

[
    { names: { name: 'Pete', name;'Claus' } },
    { names: { name: 'Paul', name;'Claus' } },
    { ... }
] 

如何通过Clausreducefilter获取一个仅包含名称为 map 的对象的数组,这样的方法?

这样做 - 但不是功能性的:

var newMap = []
var map = this.array
for(var i = 0; i < map.length; i++) {
  for(var j = 0; j < map.length; j++) {
    if(map[i] && map[i].involvements[j])
      if(map[i].involvements[j].full_name === 'Claus') {
        newMap.push(map[i])
    }
  }
}
this.array = newMap 

虽然有些不太多:

 search(){
    let map = this.submissions
    .map( (x,i) => x.involvements.filter(x => x.full_name === 'Claus'))
    .filter( x => x.length != 0 )
    console.log(map)
  }

1 个答案:

答案 0 :(得分:1)

数据结构

根据您的代码,您拥有以下数据结构:

[
  {
    involvements: [
      { full_name: 'Claus' },
      { full_name: 'Peter Paker' }
    ]
  },
  // more involvements
]

代码

如果某些 involvement包含具有属性full_name的对象,您要做的是过滤。巧合的是,函数Array#filterArray#some

const search = (x, xss) =>
    xss.filter(xs => xs['involvements'].some(y => y['full_name'] === x))

search('Claus', data) 

工作代码示例

const data = [{
    involvements: [{
        full_name: 'Claus'
      },
      {
        full_name: 'Peter Parker'
      }
    ]
  },
  {
    involvements: [{
        full_name: 'Clark Kent'
      },
      {
        full_name: 'Kristin Wells'
      }
    ]
  }
]

const search = (x, xss) =>
  xss.filter(xs => xs['involvements'].some(y => y['full_name'] === x))

console.log(
  search('Claus', data)
)