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": {…} }
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?
CodePudding user response:
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);
CodePudding user response:
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);