簡體   English   中英

從數組中獲取特定的用戶信息

[英]getting specific user information from an array

我有以下功能:

function returnAge(PlayerId){
    var data = [
        {name : 'jack', isPlayer: true, games:[{id:343, age:12}, {id:3422, age :132}]},
        { id :2 , name : 'king'},
        {id: 145,   name: 'james'}
    ]


    let filteredData= data.filter(item=>item.isPlayer)
    let itemData = filteredData[0].games.find(game=>game.id===PlayerId)

    return itemData
}

console.log(returnAge(343))

如果用戶是玩家,該函數將返回具有特定ID的用戶信息。 我使用了一個過濾器,然后使用一個查找來基於過濾后的數據獲取信息。我正在尋找一種更好的方式來使用Reduce / destructor或任何其他JavaScript功能。 請感謝任何建議。

您無需使解決方案與這些功能過於復雜,只需將簡單的for-loop與功能find一起使用即可。

函數filter不合適,因為它將循環整個元素集。

 function returnAge(PlayerId) { var data = [{ name: 'jack', isPlayer: true, games: [{ id: 343, age: 12 }, { id: 3422, age: 132 }] }, { id: 2, name: 'king' }, { id: 145, name: 'james' } ] for (var item of data) if (item.isPlayer) return item.games.find(g => g.id === PlayerId); } console.log(returnAge(343)) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您只能使用功能find

 function returnAge(PlayerId){ var data = [ {name: 'jack', isPlayer: true, games:[{id:343, age:12}, {id:3422, age :132}]}, {id: 2, name: 'king'}, {id: 145, name: 'james'} ] return data.find(item=>item.isPlayer).games.find(game=>game.id===PlayerId) } console.log(returnAge(343)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM