To get distinct values from an array of objects in JavaScript, we convert the objects to JSON strings and put them in a set.
For instance, we write
const things = [];
things.push({ place: "here", name: "stuff" });
things.push({ place: "there", name: "morestuff" });
things.push({ place: "there", name: "morestuff" });
const newThings = Array.from(new Set(myData.map(JSON.stringify))).map(
JSON.parse
);
to call myData.map
with JSON.stringify
to return an array of JSON strings converted from the objects in the things
array.
And then we convert the array to a set with Set
to remove the duplicate strings.
Next we call Array.from
to convert the set back to an array.
And then we call map
with JSON.parse
to convert the JSON strings back to objects.