我刚开始反应,所以请保持温柔。 我有一个相对扁平的JS文件,其中包含一些问题。看起来像这样:
export default [
{
category: 'General Questions',
title: 'Question 1?',
content:'Answer 1',
},
{
category: 'Pricing',
title: 'Question 2?',
content:'Answer 2',
},
我在整个文件中有多个类别。我想做的是创建所有唯一类别的列表。因此用户只会看到
我可以在此处使用filter
函数来获取所有内容:
getFaqContent() {
return filter(item => {
return item.featured;
}, Faqs);
}
如何才能获得唯一的类别?
答案 0 :(得分:1)
您可以再次使用.filter()
来选择唯一的类别(从this question的帮助中获取):
const questions = [
{
category: 'General Questions',
title: 'Question 1?',
content:'Answer 1',
},
{
category: 'Pricing',
title: 'Question 2?',
content:'Answer 2',
},
{
category: 'Pricing',
title: 'Question 2?',
content:'Answer 2',
}];
const cats = questions.map(q => q.category);
console.log(
cats.filter((q, idx) =>
cats.indexOf(q) === idx)
);
此外,您还可以使用ES6的新Set()功能,并使用ES6 spread syntax将其转换回数组:
const questions = [
{
category: 'General Questions',
title: 'Question 1?',
content:'Answer 1',
},
{
category: 'Pricing',
title: 'Question 2?',
content:'Answer 2',
},
{
category: 'Pricing',
title: 'Question 2?',
content:'Answer 2',
}];
const cats = [...new Set(questions.map(q => q.category))];
console.log(cats);
答案 1 :(得分:0)
使用ES6的优雅解决方案:
const categories = yourList.map(x => x.category);
const uniqueCategories = [...new Set(categories)];
答案 2 :(得分:0)
您可以使用reduce()
来调用uniqueBy(array, 'category')
,其中array
将成为您的数据
function uniqueBy(arr, prop){
return arr.reduce((a, d) => {
if (!a.includes(d[prop])) { a.push(d[prop]); }
return a;
}, []);
}
var categories = uniqueBy(array, 'category')
console.log(ages); //['General Questions', 'Pricing' ]