Home > Net >  Easy Way to Convert iterate JSON Array with duplicates and create new JSON Array with same Old JSON
Easy Way to Convert iterate JSON Array with duplicates and create new JSON Array with same Old JSON

Time:08-05

I want to convert a duplicate JSON Array to unique JSON Array and want another param in new JSON each element {repeated:}

    duplicateJSON =[{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"3",name:"test3"}]

Need to form another JSON with below requirement

uniqueJSON=[{id:"1",name:"test1",repeated:2},{id:"2",name:"test2",repeated:2},{id:"3",name:"test3",repeated:1}

I don't want any duplicates in the output just need to get repeated count

CodePudding user response:

Something like:

    const arr = [
  {
    partNum: "ACDC1007",
    brandName: "Electric",
    supplierName: "Electric",
  },
  {
    partNum: "ACDC1007",
    brandName: "Electric",
    supplierName: "Electric",
  },
  {
    partNum: "ACDC1007",
    brandName: "Electric",
    supplierName: "Electric",
  },
  {
    partNum: "ACDC1009",
    brandName: "Electric",
    supplierName: "Electric",
  },

  {
    partNum: "ACDC1000",
    brandName: "Electric",
    supplierName: "Electric",
  },
];

const countDict = arr.reduce((acc, curr) => {
  const { partNum } = curr;
  if (acc[partNum])   acc[partNum];
  else acc[partNum] = 1;
  return acc;
}, {});

const result = arr.map((obj) => {
  obj["count"] = countDict[obj.partNum];
  return obj;
});

console.log(result);

results in:

[
  {
    "partNum": "ACDC1007",
    "brandName": "Electric",
    "supplierName": "Electric",
    "count": 3
  },
  {
    "partNum": "ACDC1007",
    "brandName": "Electric",
    "supplierName": "Electric",
    "count": 3
  },
  {
    "partNum": "ACDC1007",
    "brandName": "Electric",
    "supplierName": "Electric",
    "count": 3
  },
  {
    "partNum": "ACDC1009",
    "brandName": "Electric",
    "supplierName": "Electric",
    "count": 1
  },
  {
    "partNum": "ACDC1000",
    "brandName": "Electric",
    "supplierName": "Electric",
    "count": 1
  }
]

CodePudding user response:

This is a simple way to remove duplicate items from the Array of objects:

let duplicateJSON = [
  { id: '1', name: 'test1' },
  { id: '2', name: 'test2' },
  { id: '1', name: 'test1' },
  { id: '2', name: 'test2' },
  { id: '3', name: 'test3' },
];

let uniqueJSON = [... new Map(duplicateJSON.map((item)=>[item["id"], item])).values()]
console.log(uniqueJSON);

  • Related