我有一个对象数组。每个对象内都有另一个数组。 我想从这些数组中提取不同的值。
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']
答案 0 :(得分:4)
您可以使用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']
答案 1 :(得分:1)
您还需要从设计中挑选一套。
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'] }],
unique = data.reduce((s, { designs }) => [...new Set([...s, ...designs])], []);
console.log(unique);
答案 2 :(得分:0)
一个简单的解决方案是:
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']}
];
var uniqueLetters = []
data.forEach(obj => {
obj.designs.forEach(letter => {
if (uniqueLetters.indexOf(letter) < 0) {
uniqueLetters.push(letter)
}
})
})
console.log(uniqueLetters)
答案 3 :(得分:0)
尝试一下。纯JavaScript解决方案。
var output = [];
for(var i=0; i<data.length; i++){
for(var j=0; j<data[i].designs.length; j++ ){
if(output.indexOf(data[i].designs[j]) === -1) {
output.push(data[i].designs[j])
}
}
}
console.log(output)
//expected output for designs ['A','B','C','D']