0

Alright so I am making a project using Hypixel's API, it will fetch all of the friends of a specific (predetermined) user and save their UUIDs to a JSON file. Sadly, due to Hypixel having a poorly maintained API there is a glitch that causes the target player's uuid to show up in the JSON file multiple times. Does anybody know how to use node edit-json-file to check for and remove duplicates?

const fetch = require("node-fetch")
const uuid = "b5cc9c1b-aeb6-4b3d-9ee6-31f608e6e9f0"
const editJsonFile = require("edit-json-file");
let file = editJsonFile(`${__dirname}/filename.json`);

const fetched = (`https://api.hypixel.net/friends?uuid=${uuid}&key=f0f0d96b-4789-4702-b3b7-58adf3015a39`);
fetch(fetched)
    .then(res => res.json())
    .then(json => {

      const friendCount = (Object.keys(json.records).length);
      var i;
      for (i = 0; i < friendCount; i++) {
        file.append("names", { uuid: json.records[i].uuidReceiver }); 
      }
      });

      file.save();
file = editJsonFile(`${__dirname}/filename.json`, {
    autosave: true
});```
jasie
  • 2,192
  • 10
  • 39
  • 54
Divlocket
  • 1
  • 1
  • 2

2 Answers2

0

Well this is how you could do it.

// ditinct the currentNames in the file, if you are sure that there is a duplicated values right now.
var names = file.get("names").reduce((acc, value) => {
  if (!acc.find(x => x.uuid == value.uuid))
    acc.push(value)
  return acc;
}, []);
// Append the fetched uuidReceiver to the currentnames and check for duplicated
var allNames = json.records.reduce((acc, value) => {
  if (!acc.find(x => x.uuid == value.uuidReceiver))
    acc.push({
      uuid: value.uuidReceiver
    });
  return acc;
}, names);
// set names in the file
file.set("names", allNames);
file.save()
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
0

I don't know if edit-json-file has methods for doing what you are asking. But you can easily add it to your code:

.then(json => {
   const uuids = {}
   json.records.map(record => uuids[record.uuidReceiver]=true);
   Object.keys(uuids).forEach(uuid => file.append("names", { uuid: uuid })); 
   file.save()
})

The uuids object will only have unique entries of uuidReceiver.

Harry
  • 103
  • 7