2 回答
TA贡献1848条经验 获得超10个赞
var data = [
{ id: 0, category: 'RINGS', type: 'CH' },
{ id: 1, category: 'NECKLACE', type: 'CHE' },
{ id: 2, category: 'PENDANT', type: 'CH' },
{ id: 3, category: 'BRACELET', type: 'CH' },
{ id: 4, category: 'RINGS', type: 'HBR' },
{ id: 5, category: 'PENDANT', type: 'CHE' }
];
const categories = [], types = [];
data.forEach((item) => {
if (!categories.includes(item.category)) {
categories.push(item.category);
}
if (!types.includes(item.type)) {
types.push(item.type);
}
});
const category = categories.map((item) => ({
name: item.toLowerCase(),
id: item
}));
const type = types.map((item) => ({ name: item, id: item }));
console.log(category);
console.log(type);
TA贡献1890条经验 获得超9个赞
至少有两种方法可以做到这一点:
使用
Array.includes
。正如上面提到的@baymax,您可以使用过滤数组includes
。在 Javascript 中使用
Set
。查看代码。
const data = [
{id: 0, category: "RINGS", type: "CH"},
{id: 1, category: "NECKLACE", type: "CHE"},
{id: 2, category: "PENDANT", type: "CH"},
{id: 3, category: "BRACELET", type: "CH"},
{id: 4, category: "RINGS", type: "HBR"},
{id: 5, category: "PENDANT", type: "CHE"},
];
// by includes
const uniqueCategories = [];
const uniqueTypes = []
data.forEach(entry => {
if (!uniqueCategories.includes(entry.category)){
uniqueCategories.push(entry.category)
}
if (!uniqueTypes.includes(entry.type)){
uniqueTypes.push(entry.type)
}
})
const categoriesMap = uniqueCategories.map(category => ({name: category.toLowerCase(), id: category}));
const typesMap = uniqueTypes.map(typeEntry => ({name: typeEntry, id: typeEntry}));
// by set
const categoriesSet = new Set()
const typesSet = new Set()
data.forEach(entry => {
categoriesSet.add(entry.category);
typesSet.add(entry.type);
});
const uniqueCategoriesFromSet = Array.from(categoriesSet).map(category => ({name: category.toLowerCase(), id: category}));
const uniqueTypesFromSet = Array.from(typesSet).map(typeEntry => ({name: typeEntry, id: typeEntry}));
console.log(uniqueCategoriesFromSet, uniqueTypesFromSet);
console.log(categoriesMap, typesMap)
添加回答
举报