首页 > 解决方案 > Distinct values from Array inside Array of objects

问题描述

Ive got an array of objects. Inside each object there is another array. I want to extract distinct values from these arrays.

var data = [
            {categorie: 'Stuff', type: 'One', designs: ['A', 'B']},
            {categorie: 'Stuff', type: 'Two', designs: ['C']},
            {categorie: 'Stuff', type: 'One', designs: ['D']},
            {categorie: 'Other', type: 'Three', designs: ['C', 'D']}
        ];
console.log([...new Set(data.map(x => x.categorie))]);
console.log([...new Set(data.map(x => x.type))]);

//expected output for designs ['A','B','C','D']

标签: javascript

解决方案


您可以使用flatMap()而不是map()

var data = [
            {categorie: 'Stuff', type: 'One', designs: ['A', 'B']},
            {categorie: 'Stuff', type: 'Two', designs: ['C']},
            {categorie: 'Stuff', type: 'One', designs: ['D']},
            {categorie: 'Other', type: 'Three', designs: ['C', 'D']}
        ];

console.log([...new Set(data.flatMap(x => x.designs))]);

//expected output for designs ['A','B','C','D']

如果您的浏览器不支持flatMap(),那么您可以使用concat()扩展运算符。

var data = [
            {categorie: 'Stuff', type: 'One', designs: ['A', 'B']},
            {categorie: 'Stuff', type: 'Two', designs: ['C']},
            {categorie: 'Stuff', type: 'One', designs: ['D']},
            {categorie: 'Other', type: 'Three', designs: ['C', 'D']}
        ];

console.log([...new Set([].concat(...data.map(x => x.designs)))]);

//expected output for designs ['A','B','C','D']


推荐阅读