我从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)
}
根据您的代码,您具有以下数据结构:
[
{
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)
)