javascript - 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']
解决方案
您可以使用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']
推荐阅读
- numpy - PIL 如何处理具有负值的 numpy 矩阵?
- oracle - SQL UNION 优化
- python - cx_oracle.NotsupportedError:在 python 中执行查询时不支持类型元组的 Python 值
- django - 使用 django-crispy-forms 的 Bootstrap4 自定义文件输入?
- android - 如何在两个特定日期之间获取 Firebase 记录?
- algorithm - 如何通过“之前”和“之后”实现“依赖解析器”?
- javascript - 使用 react-native(javascript) 在 Firestore 中的文档参考
- python - 如何获取 Flask url 的特定部分
- spring - 在 Spring 的 .xml 文件中
属性已弃用? - rxjs - 使用 RxJS 的工作流运行器