【问题标题】:NodeJS : Remove duplicate fields from objectNodeJS:从对象中删除重复字段
【发布时间】:2021-10-12 19:42:21
【问题描述】:

好吧,我正在使用 Hypixel 的 API 制作一个项目,它将获取特定(预定)用户的所有朋友并将他们的 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
});```

【问题讨论】:

    标签: javascript json hypixel-api


    【解决方案1】:

    嗯,这就是你可以做到的。

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

    【讨论】:

      【解决方案2】:

      我不知道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 的唯一条目。

      【讨论】:

        猜你喜欢
        • 2021-06-12
        • 2014-10-14
        • 1970-01-01
        • 2021-06-03
        • 2015-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        相关资源
        最近更新 更多