Robin De Wolf
Robin De Wolf

Reputation: 35

JS: JSON array remove entries with duplicate primary key

I have an API that returns a JSON with items and I receive the JSON in VUEJS. I then reflect the data inside a vfor element, however, there are many duplicate keys.

So I want to remove the objects with duplicate primary keys in a JSON array for example:

{
  {
    "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"
  },
}

In the example above I would like to remove all objects where the ID already exists with the following outcome:

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

I tried the following JS code in the past but to no avail:

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);
        });

Upvotes: 1

Views: 662

Answers (1)

Hassan Imam
Hassan Imam

Reputation: 22544

You can use array#reduce to get a unique object based on id in an object lookup and then get an array of objects using 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; }

Upvotes: 1

Related Questions