简体   繁体   中英

Add Quotes to Object Key

I'm working on a web scraper to pull basketball stats for a given player during a specific season. I've come to the point where I place the formatted player stats into an object from a master "game" array, which contains objects corresponding to the statistics for each individual game. Here's how I'm adding the stats to the player object:

        player.push({
            date: game[0],
            location: location,
            opp: game[3],
            gameType: game[4],
            result: game[5],
            start: game[6],
            min: game[7],
            fgm: game[8],
            fga: game[9],
            fgp: game[10],
            twoPM: game[11],
            twoPA: game[12],
            twoP: game[13],
            threePM: game[14],
            threePA: game[15],
            threeP: game[16],
            ftm: game[17],
            fta: game[18],
            ftp: game[19],
            orb: game[20],
            drb: game[21],
            ast: game[23],
            stl: game[24],
            blk: game[25],
            to: game[26],
            pf: game[27],
            pts: game[28]
        });

This all works as expected and the console.log output contains game objects within a final player array. Here's an excerpt:

[
  {
    date: '2019-03-22',
    location: 'neutral',
    opp: 'Ohio State',
    gameType: 'NCAA',
    result: 'L',
    start: '0',
    min: '4',
    fgm: '0',
    fga: '0',
    fgp: '',
    twoPM: '0',
    twoPA: '0',
    twoP: '',
    threePM: '0',
    threePA: '0',
    threeP: '',
    ftm: '0',
    fta: '0',
    ftp: '',
    orb: '0',
    drb: '1',
    ast: '0',
    stl: '0',
    blk: '1',
    to: '0',
    pf: '0',
    pts: '0'
  }
]

My problem is the lack of quotes around the object value. For example, in the above it displays date instead of "date". Since I'm putting this into a Mongo DB, the quotes around the object keys are (I believe) required for saving a document. How can I add these quotations around the object keys without giving myself carpal tunnel and doing it manually for each key?

Thanks in advance for the help!

You can use JSON.stringify

JSON.stringify(player, null, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM