Lodash - 按字符串 1,2 过滤
Lodash - filter by string 1,2
我有字符串
"1,2" // which is from the db.field
我正在尝试使用 lodash 进行过滤,并且像下面这样的东西起作用了
_.filter(jsonArray, function(res) { return (res.id == 1 || res.id == 2); });
请假设jsonArray如下:
[
{ 'id': '1', 'age': 60 },
{ 'id': '2', 'age': 70 },
{ 'id': '3', 'age': 22 },
{ 'id': '4', 'age': 33 }
];
这里的问题是我需要拆分 sting 1,2 并应用,
但请注意,1,2 并不总是 1,2 - 它可能是 1,2,3,并且此字符串是 db.field.
的动态字符串
现在我正在搜索是否有任何方法可以只使用字符串 say like
-.filter(jsonArray, function(res){ return res.id <is equal to one of the value in 1,2,3,4 >})
我认为将此字符串拆分为数组很明显......但我不确定是否这样做,请帮忙。
您首先需要拆分db.field
使其成为ids
的数组,以便在匹配项目时可以轻松评估。接下来,使用 filter() that you've already constructed to check if such items match the ids
using includes.
var ids = db.field.split(',').map(Number);
var result = _.filter(jsonArray, function(res) {
return _.includes(ids, res.id);
});
var db = { field: '1,2' };
var jsonArray = [
{ 'id': 1, 'age': 60 },
{ 'id': 2, 'age': 70 },
{ 'id': 3, 'age': 22 },
{ 'id': 4, 'age': 33 }
];
var ids = db.field.split(',').map(Number);
var result = _.filter(jsonArray, function(res) {
return _.includes(ids, res.id);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.12.0/lodash.min.js"></script>
我有字符串
"1,2" // which is from the db.field
我正在尝试使用 lodash 进行过滤,并且像下面这样的东西起作用了
_.filter(jsonArray, function(res) { return (res.id == 1 || res.id == 2); });
请假设jsonArray如下:
[
{ 'id': '1', 'age': 60 },
{ 'id': '2', 'age': 70 },
{ 'id': '3', 'age': 22 },
{ 'id': '4', 'age': 33 }
];
这里的问题是我需要拆分 sting 1,2 并应用,
但请注意,1,2 并不总是 1,2 - 它可能是 1,2,3,并且此字符串是 db.field.
的动态字符串现在我正在搜索是否有任何方法可以只使用字符串 say like
-.filter(jsonArray, function(res){ return res.id <is equal to one of the value in 1,2,3,4 >})
我认为将此字符串拆分为数组很明显......但我不确定是否这样做,请帮忙。
您首先需要拆分db.field
使其成为ids
的数组,以便在匹配项目时可以轻松评估。接下来,使用 filter() that you've already constructed to check if such items match the ids
using includes.
var ids = db.field.split(',').map(Number);
var result = _.filter(jsonArray, function(res) {
return _.includes(ids, res.id);
});
var db = { field: '1,2' };
var jsonArray = [
{ 'id': 1, 'age': 60 },
{ 'id': 2, 'age': 70 },
{ 'id': 3, 'age': 22 },
{ 'id': 4, 'age': 33 }
];
var ids = db.field.split(',').map(Number);
var result = _.filter(jsonArray, function(res) {
return _.includes(ids, res.id);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.12.0/lodash.min.js"></script>