[英]Javascript using .filter on nested arrays
我希望有一種方法可以將.filter()
用於嵌套array
以使事情在眼睛上更容易一些。
這是我想要的基本示例。
[
{
people: [
{
name: 'sam',
id: 1
}
{
name: 'john',
id: 2
}
]
},
people: [
{
name: 'marry',
id: 1
},
{
name: 'paul',
id: 1
}
]
},
...
]
我可以使用.filter
獲取所有ID為1的人嗎?
我可以通過將.filter
與
for(...){
for(...){
...
}
...
}
但是我並不是真的想要嵌套循環,因為這會增加不必要的復雜性。
編輯:我想輸出看起來像嵌套的人對象的單個數組
[{
name: 'sam',
id: 1
},
{
name: 'john',
id: 1
},
{
name: 'john',
id: 1
]
您可以使用Array#filter
和Array#map
。
var arr = [{people:[{name:'sam',id:1},{name:'john',id:2}]},{people:[{name:'marry',id:1},{name:'paul',id:1}]}], res = [].concat(...arr.map(v => v.people.filter(c => c.id == 1))); console.log(res);
filter
當然可以成為解決方案的一部分:
const people = [];
for (const obj of data) {
people.push(...obj.people.filter(p => p.id === 1));
}
const data = [ { people: [ { name: 'sam', id: 1 }, { name: 'john', id: 2 } ] }, { people: [ { name: 'marry', id: 1 }, { name: 'paul', id: 1 } ] } ]; const people = []; for (const obj of data) { people.push(...obj.people.filter(p => p.id === 1)); } console.log(people);
.as-console-wrapper { max-height: 100% !important; }
(如果願意,可以使用data.forEach
而不是for-of
循環。)
您可以使用ES5方法來合並過濾后的數組。
var array = [{ people: [{ name: 'sam', id: 1 }, { name: 'john', id: 2 }] }, { people: [{ name: 'marry', id: 1 }, { name: 'paul', id: 1 }] }], result = [].concat.apply([], array.map(function (a) { return a.people.filter(function (p) { return p.id === 1; }); })); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.