如何使用underscore.js过滤列表元素中带有匹配参数的对象?
how to filter those objects with match parameter in list element using underscore.js?
nodedatasource = [
{"id":1,'name':'a'},
{"id":2,'name':'b'},
{"id":3,'name':'c'},
{"id":4,'name':'d'},
]
list_ids = [3,2] #
我想获得一个过滤后的数据源对象列表,其 id 在 list_ids?
我尝试过这种方法。
..需要更正
datanode =_.filter(nodedatasource, function(element,ids){
return element.id in ids
})
const list_ids = [3, 2]
const datanode =_.filter(nodedatasource,function(element){
return list_ids.includes( element.id )
})
//datanode = [{"id":2,'name':'b'},
// {"id":3,'name':'c'}]
如果你只想纯粹地做这件事 JavaScript
var datasource = [{"id":1,'name':'a'},
{"id":2,'name':'b'},
{"id":3,'name':'c'},
{"id":4,'name':'d'},
]
var list_ids = [3,2]
var filteredArray = datasource.filter(elem => list_ids.includes(elem.id));
console.log(filteredArray)
另一种完全在 underscorejs 中完成的方法:
list_ids = [3, 2]
datanode = _.filter(nodedatasource,function(element,list_ids){
return _.contains(list_ids,element.id)
});
//datanode = [{"id":2,'name':'b'},
// {"id":3,'name':'c'}]
nodedatasource = [
{"id":1,'name':'a'},
{"id":2,'name':'b'},
{"id":3,'name':'c'},
{"id":4,'name':'d'},
]
list_ids = [3,2] #
我想获得一个过滤后的数据源对象列表,其 id 在 list_ids?
我尝试过这种方法。
..需要更正
datanode =_.filter(nodedatasource, function(element,ids){
return element.id in ids
})
const list_ids = [3, 2]
const datanode =_.filter(nodedatasource,function(element){
return list_ids.includes( element.id )
})
//datanode = [{"id":2,'name':'b'},
// {"id":3,'name':'c'}]
如果你只想纯粹地做这件事 JavaScript
var datasource = [{"id":1,'name':'a'},
{"id":2,'name':'b'},
{"id":3,'name':'c'},
{"id":4,'name':'d'},
]
var list_ids = [3,2]
var filteredArray = datasource.filter(elem => list_ids.includes(elem.id));
console.log(filteredArray)
另一种完全在 underscorejs 中完成的方法:
list_ids = [3, 2]
datanode = _.filter(nodedatasource,function(element,list_ids){
return _.contains(list_ids,element.id)
});
//datanode = [{"id":2,'name':'b'},
// {"id":3,'name':'c'}]