我有绳子
"1,2" // which is from the db.field我试着用房客过滤,下面的一些东西起作用了
_.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 }
];问题是我需要把毒刺1,2分开,然后应用,
但是请注意,1,2并不总是1,2 -它可能是1,2,3,并且这个字符串是来自db.field的动态的。
现在我正在搜索是否有任何方法可以使用字符串,比如
-.filter(jsonArray, function(res){ return res.id <is equal to one of the value in 1,2,3,4 >})我觉得很明显,把这个字符串分成数组.但我不能肯定,请帮帮忙。
发布于 2016-05-21 17:31:29
首先,您需要将db.field拆分为ids数组,在匹配项时可以轻松地对其进行评估。接下来,使用您已经构建的过滤器()来检查这些项是否与使用包括的ids匹配。
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>
https://stackoverflow.com/questions/37365725
复制相似问题