我有一個 id 陣列,使用這個 id 陣列,我想過濾在另一個父陣列中找到的物件陣列。
這是 id 陣列:
[1, 2, 3, 4, 5]
這是在其中找到物件陣列的陣列
[
answers: [
{
id: 1,
name: 'test'
},
{
id: 2,
name: 'test2'
},
{
id: 10,
name: 'test2'
},
]
question: 'Question text"
]
現在我正在努力過濾物件陣列(答案)以檢索其 id 與陣列中的任何 id 匹配的物件。因此,在此示例中,我期待以下結果:
answers: [
{
id: 1,
name: 'test'
},
{
id: 2,
name: 'test2'
}
]
由于 id 陣列,我有 [1, 2],我想過濾答案陣列以檢索 id 1 和 2 的物件。
我嘗試了各種回圈方法,例如過濾器和映射,但我無法獲得想要的結果。任何幫助,將不勝感激。
uj5u.com熱心網友回復:
你可以使用filter()和includes()
const data = {
answers: [{
id: 1,
name: 'test'
},
{
id: 2,
name: 'test2'
},
{
id: 10,
name: 'test2'
},
],
question: 'Question text'
}
const ids = [1, 2];
const result = data.answers.filter(a => ids.includes(a.id));
console.log(result);
uj5u.com熱心網友回復:
先做幾個更正:
answers并且question應該是物件的屬性- 匹配結束
Question text與開口'而不是"
你可以使用Array#filterandArray#includes方法如下,當然,withArray#map方法:
const filters = [1, 2, 3, 4, 5],
input = [ {answers: [ { id: 1, name: 'test' }, { id: 2, name: 'test2' }, { id: 10, name: 'test2' } ], question: 'Question text'} ],
output = input.map(
({
answers,
...rest
}) => ({
answers: answers.filter(({id}) => filters.includes(id)),
...rest
})
);
console.log( output );
uj5u.com熱心網友回復:
試試這個: const filters = secondArr.answers.filter((f)=>(arr.some((e)=>e===f.id)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/464750.html
