2016-10-10 122 views
0

我有以下数据:如何过滤使用lodash值数组嵌套对象?

var jobs = [ 
{ 
job_type: "Part Time", 
latitude: 49.545068, 
longitude: 0.760518, 
title: "reiciendis", 
industry: [ 
    { 
    id: 1, 
    name: "development" }, 
    { 
    id: 2, 
    name: "design" 
    } 
]}, 
{ 
job_type: "Full Time", 
latitude: 51.545068, 
longitude: 0.460518, 
title: "auteas", 
industry: [ 
    { 
    id: 1, 
    name: "development" }, 
    { 
    id: 2, 
    name: "testing" 
    } 
] 

,我想尝试和筛选器可以根据用户的搜索结果的参数,行业的求职,其中填充数组即选择:

var jobchoices = ["testing", "design"]; 

我lodash过滤到目前为止是这样的:

var self = this 

return _.filter(this.jobs, function(item) { 
    return _.filter(item.industry, function(obj) { 
     return _.some(self.jobchoices, obj.name); 
    }); 
}); 

但所有作业返回true。这是我第一次使用lodash。我究竟做错了什么?其次,我能以这种方式继续由其他用户选择的过滤器链,由作业类型说呢?

+0

是不是'development','testing'和'design'应该是字符串? –

+0

你说得对。更新。 – BJacks

回答

0

可以使用_.filter您试图检索作为最终结果,然后使用_.chain与_.map和_.intersection过滤内部的对象数组的主阵列。

喜欢的东西代码波纹管就足够了,虽然它不是漂亮。

var self = this; 

_.filter(jobs, function(job) { 

    return _.chain(job.industry) 
    .map('name') 
    .intersection(self.jobchoices) 
    .size() 
    .gt(0) 
    .value() 
}) 

(仅适用于最新lodash测试 - v4.16.4)

0

应该所有作业返回true,因为在你的数据。例如两个作业jobs具有匹配industry项目。如果你改变你的jobchoices阵列有一个项目(或多个项目),只有符合您jobs之一,可能是这个样子(香草JS):

var matches = jobs.filter(function(job) { 
    return job.industry.some(function(industry) { 
    return jobchoices.indexOf(industry.name) > -1; 
    }); 
}); 

还是ES6相当于:

let matches = jobs.filter(({industry} => industry.some(({name}) => jobchoices.includes(name))); 

至于你要去哪里错了,你的顶级_.filter将返回另一个_.filter(它会返回一个阵列 - 是truthy - 因此,所有的项目将被退回)。你应该能够修改原来的代码返回内_.filter通话的长度是否> 0补救:

return _.filter(this.jobs, function(item) { 
    var matchingIndustries = _.filter(item.industry, function(obj) { 
     return _.some(self.jobchoices, obj.name); 
    }); 
    return matchingIndustries.length > 0; 
}); 
+0

谢谢。我应该澄清的是,工作阵列是样品,还有其他条目不同行业的工作。 – BJacks

相关问题