我从API获得以下数据:
[
{ names: { name: 'Pete', name;'Claus' } },
{ names: { name: 'Paul', name;'Claus' } },
{ ... }
]
如何通过Claus
,reduce
,filter
获取一个仅包含名称为 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)
}
答案 0 :(得分:1)
根据您的代码,您拥有以下数据结构:
[
{
involvements: [
{ full_name: 'Claus' },
{ full_name: 'Peter Paker' }
]
},
// more involvements
]
如果某些 involvement
包含具有属性full_name
的对象,您要做的是过滤。巧合的是,函数Array#filter
和Array#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)
)