0

Is there the best possible way to remove duplicate entries from an array of objects? My goal is to have such an array

Array(2) [ {…}, {…}]

​
0: Object { "B72E9DD4-0851-432D-B9CB-1F74EC3F83CC": {…} }

1: Object { "A0C3DBF7-F090-43AA-8FAC-E823AE23B3FF": {…} }

enter image description here

what I am trying to do is later after removing the duplicate entries from the array i want to loop through the array and store the information in a object in such a way refer below image . Is that possible that the newarray can be converted in such manner?

enter image description here

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – Daniel Black Sep 01 '22 at 20:51
  • 1
    Does this answer your question? [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – pilchard Sep 01 '22 at 20:55
  • [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Heretic Monkey Sep 02 '22 at 12:06

2 Answers2

0

To remove the duplicate entries we can check if each identifier (e.g: "B72E9DD4...") has been added already to the resulting object when iterating over the array

let myArray = [
  {"B72E9DD4-0851-432D-B9CB-1F74EC3F83CC": {}},
  {"A0C3DBF7-F090-43AA-8FAC-E823AE23B3FF": {}},
  {"A0C3DBF7-F090-43AA-8FAC-E823AE23B3FF": {}},
  {"A0C3DBF7-F090-43AA-8FAC-E823AE23B3FF": {}},
];

// Declare object which is going to contain the unique values
let result = {};

// Iterating over the array 
myArray.forEach((obj) => {
  // destructuring the current object into key value pairs 
  // (e.g: ["A0C3DBF7...", {}]
  for (const [key, value] of Object.entries(obj)) {
    // checking if the key (e.g: "A0C3DBF7...") has
    // been added already
    if (!result[key]) {
      // If it hasn't been added, set a property with the key
      // as name and set the value too
      result[key] = value;
    }
  }
});

console.log(result);
Victor Santizo
  • 1,145
  • 2
  • 7
  • 16
0

Instead of first removing the duplicates from an array and then make the result object, You can directly create the final object based on the input array.

Here is the live demo :

const arr = [{
    "B72E9DD4": {}
}, {
    "A0C3DBF7": {}
}, {
    "A0C3DBF7": {}
}, {
    "A0C3DBF7": {}
}];

const result = {};

arr.forEach(obj => {
  if (!result[Object.keys(obj)[0]]) {
    result[Object.keys(obj)[0]] = obj[Object.keys(obj)[0]]
  }
});

console.log(result);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123