2016-10-31 8 views
-1

私は、次のような単純なJSON配列があります。複数の値に基づいて配列をフィルタリングし

const personList = [ 
{ 
    id: 1, 
    name: "Phil" 
}, 
{ 
    id: 2, 
    name: "Bren" 
}, 
{ 
    id: 3, 
    name: "Francis Underwood" 
}, 
{ 
    id: 4, 
    name: "Claire Underwood" 
}, 
{ 
    id: 5, 
    name: "Ricky Underwood" 
}, 
{ 
    id: 6, 
    name: "Leo Boykewich" 
} 
]; 

をそして私は[1,4]で渡されるようなものので、IDの配列を渡すことで、これをフィルタリングしたいと思います

getAttendeesForEvent: (attendeeIds) => { 
    if (attendeeIds === undefined) return Promise.reject("No attendee id provided"); 

    return Promise.resolve(personList.filter(x => x.id == [attendeeIds]).shift()); 
} 

I:それは唯一

は、この関数がどのように見えるかですが、私はそれが間違っているattendeeIdsを知っている[1、4]で渡された配列の「フィル」と「クレア・アンダーウッド」をされて戻ってきます持っていないJSを何年も使用しています。私は例を探しましたが、私は達成しようとしているものすべてが複雑すぎるようです。それで、渡されたIDの配列に基づいてこれをどのようにフィルタリングできますか?

+0

あなたが約束を返却されるいくつかの特別な理由はありますか? –

答えて

1
return Promise.resolve(personList.filter(x => attendeeIds.indexOf(x.id) !== -1)); 

あなたのルーピングされた各アイテムのIDが出席者の内部に存在するかどうかを確認する必要があります。これを行うには、フィルターの内部でArray.indexOfを使用します。

これは{ id: #, name: String }のオブジェクトの配列を返します。

これらのオブジェクトの名前だけを返す場合は、後でマップを実行して、指定した関数を使用して配列を別の配列に変換します。

const filteredNames = personList 
    .filter(x => attendeeIds.indexOf(x.id) !== -1) 
    .map(x => x.name); 
// ['Phil', 'Claire Underwood'] 
+0

ありがとうございました! – graffixnyc

1

これらの行には何かできます。お役に立てれば。

const personList = [{ 
 
    id: 1, 
 
    name: "Phil" 
 
}, { 
 
    id: 2, 
 
    name: "Bren" 
 
}, { 
 
    id: 3, 
 
    name: "Francis Underwood" 
 
}, { 
 
    id: 4, 
 
    name: "Claire Underwood" 
 
}, { 
 
    id: 5, 
 
    name: "Ricky Underwood" 
 
}, { 
 
    id: 6, 
 
    name: "Leo Boykewich" 
 
}]; 
 
let attendeeIds = [1, 5]; 
 

 
let getAttendeesForEvent =() => { 
 
    return new Promise(function(resolve, reject) { 
 

 
    if (attendeeIds === undefined) { 
 
     reject("No attendee id provided"); 
 
    } else { 
 
     resolve(personList.filter((x) => attendeeIds.includes(x.id)).map((obj) => obj.name)); 
 
    } 
 
    }); 
 
} 
 

 
getAttendeesForEvent().then((data) => console.log(data))

関連する問題