{
"id": 1,
"name": "Тест",
"popularity": 4,
"published_at": "2021-07-22T20:18:08.000Z",
"created_at": "2021-07-11T23:33:52.000Z",
"updated_at": "2021-07-22T20:19:37.000Z",
"slug": "test",
"price": 3000,
"sale": 2000,
"variations": [
{
"id": 1,
"color": {
"id": 1,
"name": "Черный",
"slug": "chernyj",
"published_at": "2021-07-22T20:00:25.000Z",
"created_at": "2021-07-22T20:00:24.000Z",
"updated_at": "2021-07-22T20:00:26.000Z"
},
"size": {
"id": 2,
"name": "M",
"slug": "m",
"published_at": "2021-07-22T20:00:01.000Z",
"created_at": "2021-07-22T19:59:59.000Z",
"updated_at": "2021-07-22T20:00:01.000Z"
}
},
{
"id": 2,
"color": {
"id": 3,
"name": "Белый",
"slug": "belyj",
"published_at": "2021-07-22T20:00:43.000Z",
"created_at": "2021-07-22T20:00:42.000Z",
"updated_at": "2021-07-22T20:00:43.000Z"
},
"size": {
"id": 2,
"name": "M",
"slug": "m",
"published_at": "2021-07-22T20:00:01.000Z",
"created_at": "2021-07-22T19:59:59.000Z",
"updated_at": "2021-07-22T20:00:01.000Z"
}
}
],
}
[...new Set(data.variations.map(n => n.color.name))]
Object.values(Object.fromEntries(data.variations.map(n => [ n.color.name, n.color ])))
// или
Object.values(data.variations.reduce((acc, { color: n }) => (acc[n.name] ??= n, acc), {}))
// или
data.variations.map(n => n.color).filter(function(n) {
return !(this[n.name] = this.hasOwnProperty(n.name));
}, {})
function unique(data, key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set;
const result = [];
for (const n of data) {
const k = getKey(n);
!keys.has(k) && keys.add(k) && result.push(n);
}
return result;
}
// получаем массив уникальных имён цветов
const uniqueStrColors = unique(data.variations.map(n => n.color.name));
// получаем массив объектов цветов, свойства name которых уникальны
const uniqueObjColors = unique(data.variations.map(n => n.color), n => n.name);