过滤内部数组javascript

时间:2017-07-03 10:43:49

标签: javascript arrays object filter

如果数组在另一个数组中,我如何过滤?

我该如何循环呢?

var jobs = [
    {
        'id': '1',
        'departments': [{'name': 'Finance'}],
        'offices': [{'name': 'US'}, {'name': 'Brazil'}]
    },
    {
        'id': '1',
        'departments': [{'name': 'Finance'}],
        'offices': [{'name': 'Paris'}, {'name': 'China'}]
    }
];

var results = jobs.filter(function(o)) {
    return o.offices[0].name == 'US';
} // get office US;

jsFiddle Link

1 个答案:

答案 0 :(得分:1)

如果要按内部数组中可能存在的值过滤数组,可以在内部数组上使用Array#some。方法Array#some返回true,如果数组中至少有一个元素符合条件,则停止迭代。



var jobs = [{"id":"1","departments":[{"name":"Finance"}],"offices":[{"name":"US"},{"name":"Brazil"}]},{"id":"1","departments":[{"name":"Finance"}],"offices":[{"name":"Paris"},{"name":"China"}]}];

var jobsWithoutUs = jobs.filter(function(job) {
  return job.offices.some(function(office) {
    return office.name === 'US';
  });
});

console.log(jobsWithoutUs);