【问题标题】:JS: JSON array remove entries with duplicate primary keyJS:JSON数组删除具有重复主键的条目
【发布时间】:2021-06-02 10:20:12
【问题描述】:

我有一个返回带有项目的 JSON 的 API,我在 VUEJS 中接收 JSON。然后我将数据反映在一个 vfor 元素中,但是,有很多重复的键。

所以我想删除 JSON 数组中具有重复主键的对象,例如:

{
  {
    "id" : 1,
    "name": "test"
  },
  {
    "id" : 2,
    "name": "other name"
  },
  {
    "id" : 1,
    "name": "does not have to be the same name"
  },{
    "id" : 3,
    "name": "but they could be the same"
  },{
    "id" : 2,
    "name": "other name"
  },
}

在上面的示例中,我想删除 ID 已经存在的所有对象,结果如下:

{
  {
    "id" : 1,
    "name": "test"
  },
  {
    "id" : 2,
    "name": "other name"
  }{
    "id" : 3,
    "name": "but they could be the same"
  }
}

我过去尝试过以下JS代码但无济于事:

axios.get(path)
        .then((res) => {
          this.inv = res.data.descriptions;
          for (let i = 0; i < this.inv.length; i += 1) {
            Object.entries(this.inv[i]).forEach((key1, value1) => {
              Object.entries(this.inv[i]).forEach((key2, value2) => {
                if (key1 === 'instanceid' && key2 === 'instanceid') {
                  if (value1 === value2) {
                    delete this.inv[i];
                  }
                }
              });
            });
          }
        })
        .catch((error) => {
          // eslint-disable-next-line
          console.error(error);
        });

【问题讨论】:

    标签: javascript json vue.js


    【解决方案1】:

    您可以在对象查找中使用array#reduce 获取基于id 的唯一对象,然后使用object.values() 获取对象数组。

    const data = [ { "id" : 1, "name": "test" }, { "id" : 2, "name": "other name" }, { "id" : 1, "name": "does not have to be the same name" },{ "id" : 3, "name": "but they could be the same" },{ "id" : 2, "name": "other name" }, ],
          unique = Object.values(data.reduce((r, o) => {
            r[o.id] = r[o.id] || o;
            return r;
          },{}));
    console.log(unique);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 我在这个数据集上使用了代码,但它不起作用:steamcommunity.com/inventory/76561198086791620/440/2?l=english 在我的例子中,“数据”=描述
    • 请分享您的代码。另外,共享的 JSON 很大,加载到内存时没有报错吗?
    • 抱歉弄错了,你的代码有效,现在我只需要做同样的事情,但基于组合键。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 2012-05-19
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多