首页 > 解决方案 > 如何构造这个数组,分离类别和产品

问题描述

我有单个数组,我想将类别和类别产品分开

const product = [{
    id: 1,
    name: 'Cloth',
    cat: ['fashion', 'man', 'women']
}, {
    id: 2,
    name: 'Shoes',
    cat: ['fashion']
}, {
    id: 3,
    name: "hat",
    cat: ['man', 'fashion']
}]

如何从产品数组中分离类别值。

const cat = ['fashion','man','women']

如何区分类别和产品

const result = [{
    cat: 'fashion',
    [{
        id: 1,
        name: 'Cloth'
    }, {
        id: 2,
        name: 'Shoes'
    }, {
        id: 3,
        name: "hat"
    }]
}, {
    cat: 'man',
    [{
        id: 1,
        name: 'Cloth'
    }, {
        d: 3,
        name: "hat"
    }]
}, {
    cat: 'women',
    [{
        id: 1,
        name: 'Cloth'
    }]
}]

如何开发这种类型的数组请帮助我。有谁知道请帮帮我,提前坦克回复

标签: javascriptjavaarraysreactjs

解决方案


如果您要从产品数组中获取所有类别。

let allCategories = [];
product.forEach(p => {
    allCategories.push(...p.cat);
});
allCategories = [...new Set(allCategories)];

对于第二个问题,我将使用第一个问题的结果:

allCategories.forEach(categorie => {
    result.push(
        {
            cat: categorie,
            products : product.filter(p => {
                if(p.cat.includes(categorie)) {
                    return {
                        id : p.id,
                        name : p.name
                    }
                }
            })
        }
    )
})

推荐阅读