Arvind Chourasiya
Arvind Chourasiya

Reputation: 17392

How to get distinct records from JSON based on specific field

I have JSON records. Where name field has many duplicate records. Based on name I want to get distinct records. This is my data

{
    "name": "ABER",
    "value":72,
},
{
    "name": "HDCC",
    "value":72,
},
{
    "name": "HDCC",
    "value":72,
},
{
    "name": "OCL",
    "value":42,
},
{
    "name": "OCL",
    "value":42,
},

This output I am looking for

{
    "name": "OCL",
    "value":42,
},
{
    "name": "ABER",
    "value":72,
},
{
    "name": "HDCC",
    "value":72,
},

I tried this but it is returning name field only not value along with

var op= Array.from(new Set(obj.map((item: any) => item.name)))

How can I do that

Upvotes: 0

Views: 64

Answers (3)

Terry Lennox
Terry Lennox

Reputation: 30675

You can use Array.reduce to get the required result, like so:

let a = [{
    "name": "ABER",
    "value":72,
},
{
    "name": "HDCC",
    "value":72,
},
{
    "name": "HDCC",
    "value":72,
},
{
    "name": "OCL",
    "value":42,
},
{
    "name": "OCL",
    "value":42,
}]

let result = Object.values(a.reduce((res, el) => { 
    res[el.name] = { ...el, count: res[el.name] ? res[el.name].count + 1: 0};
    return res;
}, {}));

console.log(result);

Upvotes: 1

Akshay Sharma
Akshay Sharma

Reputation: 219

Use this function to get unique objects. It will resolve your problem.

const arr1 = [{
    "name": "ABER",
    "value": 72
  },
  {
    "name": "HDCC",
    "value": 72
  },
  {
    "name": "HDCC",
    "value": 72
  },
  {
    "name": "OCL",
    "value": 42
  },
  {
    "name": "OCL",
    "value": 42
  }
]

getUniqueObj = (array) => {
  var flags = [],
    output = [],
    l = array.length,
    i;
  for (i = 0; i < l; i++) {
    if (flags[array[i].name]) continue;
    flags[array[i].name] = true;
    output.push({
      name: array[i].name,
      value: array[i].value
    });
  }
  return output;
}
console.log(getUniqueObj(arr1));

Upvotes: 0

Cl&#233;ment Caillat
Cl&#233;ment Caillat

Reputation: 29

I Don't know if this is the best way, but you should check the data before inserting new. Like check if the name : ABER is already in the file, else insert it

Upvotes: 0

Related Questions