我有一个值,需要返回包含该值在属性中的对象。
var search='CPP@';
var results=_.filter(collection,{VAL:search});
我需要获取所有包含“CPP@”而不是相等的对象。我已经准备好了一个https://jsfiddle.net/licass/e87mxfqt/
我有一个值,需要返回包含该值在属性中的对象。
var search='CPP@';
var results=_.filter(collection,{VAL:search});
我需要获取所有包含“CPP@”而不是相等的对象。我已经准备好了一个https://jsfiddle.net/licass/e87mxfqt/
var collection=[
{
"DSP_MAQ": "Máquina 4",
"VAL": "CPP@4@1900-01-01"
},
{
"DSP_MAQ": "Máquina 5",
"VAL": "CMIP@5@1900-01-01"
},
{
"DSP_MAQ": "Máquina 6",
"VAL": "CMIP@6@1900-01-01"
},
{
"DSP_MAQ": "Máquina 7",
"VAL": "CMIP@7@1900-01-01"
},
{
"DSP_MAQ": "Máquina 8",
"VAL": "CPP@8@1900-01-01"
},
{
"DSP_MAQ": "Máquina 9",
"VAL": "CMIP@9@1900-01-01"
},
{
"DSP_MAQ": "Máquina 10",
"VAL": "CMIP@10@1900-01-01"
}
];
var search='CPP@';
var results=_.filter(collection,function(item){
return item.VAL.indexOf(search)>-1;
});
console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
var search='CPP@';
var results=_.filter(collection,function(item){
return item.VAL.indexOf(search)>-1;
});
console.log(results);
var results = _.filter(collection,function(obj) {
return obj.VAL.indexOf(search) !== -1;
});
2022年更新
现在甚至不需要使用lodash
了:
collection.filter(o => o.VAL.includes(search));
现在我们可以使用.filter
方法用于数组,还有.includes
方法用于数组和字符串。当然还有箭头函数!
var collection=[
{
"DSP_MAQ": "Máquina 4",
"VAL": "CPP@4@1900-01-01"
},
{
"DSP_MAQ": "Máquina 5",
"VAL": "CMIP@5@1900-01-01"
},
{
"DSP_MAQ": "Máquina 6",
"VAL": "CMIP@6@1900-01-01"
},
{
"DSP_MAQ": "Máquina 7",
"VAL": "CMIP@7@1900-01-01"
},
{
"DSP_MAQ": "Máquina 8",
"VAL": "CPP@8@1900-01-01"
},
{
"DSP_MAQ": "Máquina 9",
"VAL": "CMIP@9@1900-01-01"
},
{
"DSP_MAQ": "Máquina 10",
"VAL": "CMIP@10@1900-01-01"
}
];
var search='CMIP@9@1900-01-01';
var filterList = collection.filter(function(item) {
return item.VAL === search;
})
console.log(filterList)