【问题标题】:how to read json file and search with filter for common items in nodejs如何读取 json 文件并使用过滤器搜索 nodejs 中的常见项目
【发布时间】:2021-08-20 01:47:44
【问题描述】:

我的 JSON 文件包含游戏对象,我想获得用户之间总游戏时间最长的前 5 款游戏。

我试图通过使用 nodejs 中的文件系统读取文件来获取所有对象:

const queryGames = async () => {
    let data = fs.readFileSync(path.resolve(__dirname, '../../games.json'))
    let games = JSON.parse(data)
    return games
}

/**
 * Query for top games by play time
 * @returns {Promise<QueryResult>}
 */
const selectTopByPlaytime = async () => {

}

这是 json 文件:https://jsoneditoronline.org/#left=cloud.3b82169327044c04b7207fa186aee85b&right=local.tiniqu

【问题讨论】:

  • 你有没有尝试做点什么?
  • @RaphaelPICCOLO 我不确定我应该使用什么方法或算法

标签: node.js arrays json object search


【解决方案1】:

这样的东西应该可以工作。

const gamePlayData = require('./gamePlay.json').data

/**
 * Query for games and time
 * @returns {
      'League of legends': 1650,
      'World of warcraft': 2300,
      'Dark Souls': 218,
      'The Witcher 3: Wild Hunt': 987,
      etc....
    }
 */
const getGamePlayTimes = () => {
    gamePlayTimes = {}
    gamePlayData.forEach( (playData) => {
        const gameName = playData.game
        if(gamePlayTimes[gameName]) {
            gamePlayTimes[gameName] += playData.playTime
        }
        else {
            gamePlayTimes[gameName] = playData.playTime
        }
    })
    return gamePlayTimes;
}

const getGamesAndTimesAsList = (playTimes) => {
    let gamesWithTimeArr = [];
    let i = 0;
    for(let game in playTimes) {
        let gameAndPlayTime = {game: "", playTime: 0};
        gameAndPlayTime.game = game;
        gameAndPlayTime.playTime = playTimes[game];
        gamesWithTimeArr[i++] = gameAndPlayTime
    }
    return gamesWithTimeArr;
}


const  reverseBubbleSort = (a, par) => {
let swapped;
do {
    swapped = false;
    for (var i = 0; i < a.length - 1; i++) {
        if (a[i][par] < a[i + 1][par]) {
            var temp = a[i];
            a[i] = a[i + 1];
            a[i + 1] = temp;
            swapped = true;
        }
    }
  } while (swapped);

  return a;
}

sortedArr = reverseBubbleSort(getGamesAndTimesAsList( getGameAndPlayTimes() ) , 'playTime') 
const top5 = sortedArr.slice(0, 5);
console.log(top5);

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 2019-07-11
    • 2014-06-08
    • 1970-01-01
    • 2020-09-15
    • 2020-05-10
    • 2021-02-12
    • 2019-08-09
    • 2015-09-05
    相关资源
    最近更新 更多