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

问题描述 投票:0回答:1

我从API获得以下数据:

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

我怎样才能得到一个数组,其中只包含那些名为Claus的对象,其中包含reducefiltermap等方法?

这样做 - 但不是功能风格:

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)
  }
javascript arrays functional-programming higher-order-functions
1个回答
1
投票

Data Structure

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

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

Code

你想要做的是过滤一些involvement包含一个属性为full_name的对象。巧合的是有Array#filterArray#some的功能。

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

search('Claus', data) 

Working Code Example

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)
)
© www.soinside.com 2019 - 2024. All rights reserved.