简体   繁体   中英

How to increment values in an array json file based of from a name?

Example JSON file:

[
 {
   "discordId": "9273927302020",
   "characters": [
     {
     "name": "Rare_Character",
     "value": 1
     },
     {
     "name": "Ultra_Rare_Character",
     "value": 1
     }
   ]
 }
]

Let's just say for example I ran this simple gacha and got 4 characters:

let i = 1
var picks = []
while(i <= 4){
  const { pick } = gacha.simple(alpha)
  picks.push(pick)
  i++
}

Now, picks has an array like this:

[
  {
    "name": "Common_Character"
  },
    {
    "name": "Ultra_Rare_Character"
  },
    {
    "name": "Common_Character"
  },
    {
    "name": "Rare_Character"
  }
]

How do I increment the value in My Example JSON file based on the name from what I got in my gacha results picks while ignoring the Common_Character and only passing those Rare and Ultra_Rare ones?

I've tried filtering them like this:

var filter = picks.filter(t => t.name === 'Rare_Character' || t.name === 'Ultra_Rare_Character')

Now I don't know how to increase those values in my JSON file and what if in the gacha results I got two Rare_Characters or Ultra_Rare_Character

I'm using fs to read my JSON file but I just don't know the logic to increase values

 const src = [ { "discordId": "9273927302020", "characters": [ { "name": "Rare_Character", "value": 1 }, { "name": "Ultra_Rare_Character", "value": 1 } ] } ]; const gacha = [ { "name": "Common_Character" }, { "name": "Ultra_Rare_Character" }, { "name": "Common_Character" }, { "name": "Rare_Character" } ]; const updateValues = (src, gacha) => { const gachaSums = gacha.reduce((collector, current) => { collector[current.name] = (collector[current.name] | 0) + 1; return collector; }, {}); src.characters.forEach(srcChar => { gachaSums[srcChar.name] = srcChar.value + (gachaSums[srcChar.name] | 0); }); src.characters = Object.entries(gachaSums).map(([key, value]) => ({ name: key, value: value }) ); return src; } console.log(updateValues(src[0], gacha));

Maybe this version could help

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