2017-07-03 98 views
1

如何過濾數組是否在另一個數組內?過濾內部數組javascript

我該如何循環?

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

+3

'jobs.filter(J => j.offices.some(O => o.name === 「US」))'使用'some'以查看是否之一「辦公室」陣列內的對象符合您的要求。 – user3297291

回答

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);