1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I used the code on this dataset and it did not work: steamcommunity.com/inventory/76561198086791620/440/2?l=english in my case, "data" = descriptions
Please share your code. Also, the shared JSON is pretty big, didn't you get any error while loading it in memory?
Sorry made a mistake, your code works, now I just need to do the same but base on a combination of keys. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.