NodeJS: удалить повторяющиеся поля из объекта

avatar
Divlocket
9 августа 2021 в 03:30
87
2
0

Хорошо, поэтому я создаю проект с использованием API Hypixel, он будет получать всех друзей определенного (заранее определенного) пользователя и сохранять их UUID в файле JSON. К сожалению, из-за того, что у Hypixel плохо поддерживаемый API, возникает сбой, из-за которого uuid целевого игрока появляется в файле JSON несколько раз. Кто-нибудь знает, как использовать node edit-json-file для проверки и удаления дубликатов?

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
});```
Источник

Ответы (2)

avatar
Harry
9 августа 2021 в 04:10
0

Я не знаю, есть ли у edit-json-file методы для выполнения того, что вы просите. Но вы можете легко добавить его в свой код:

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

Объект uuids будет иметь уникальные записи только uuidReceiver.

avatar
Alen.Toma
9 августа 2021 в 04:06
0

Ну вот как можно это сделать.

// 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()