我有以下对象数组:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:
reuseIdentifier, for: indexPathOfCollectionView as IndexPath) as!
MyCustomCollectionViewCell
if(tableView == cell.graphTableView){
let cell:CustomGraphTableViewCell =
tableView.dequeueReusableCell(withIdentifier: "CustomGraphTableViewCell") as!
CustomGraphTableViewCell
return cell
}
else
{
let cell:MyCustomTableViewCell =
tableView.dequeueReusableCell(withIdentifier: "MyCustomTableViewCell") as!
MyCustomTableViewCell
cell.nameLabel.text = namesArray[indexPath.row]
return cell
}
}
我想过滤中等为True的此列表。我目前有这个设置。
var sizeList = [
{ id: 1, title:"Test1",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 2,title:"Test2",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 3,title:"Test3",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:true}]
}
]
这会不断返回一个空数组。我也试过这个:
var specificSizes = _.filter(sizeList.type, { 'name': 'Medium', 'present': true })
答案 0 :(得分:6)
使用lodash,您可以将条件包装在与测试相同的结构中,作为原始对象。
_.filter(sizeList, { type: [{ name: 'Medium', present: true }] })
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = _.filter(sizeList, { type: [{ name: 'Medium', present: true }] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
在普通的Javascript中,您可以使用Array#filter
作为外部数组,如果满足一个条件,请与Array#some
核对。
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = sizeList.filter(function (a) {
return a.type.some(function (b) {
return b.name === 'Medium' && b.present;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }