有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript如何构造此数组,将类别和产品分开

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

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'
    }]
}]

如何开发这种类型的阵列请帮助我。任何人知道请帮助我,提前回复


共 (2) 个答案

  1. # 1 楼答案

    如果您想要从产品阵列中获取所有类别,请选择一个

    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
                        }
                    }
                })
            }
        )
    })
    
  2. # 2 楼答案

    第一个答案:

    let categories = [];
        const product = [
          { id: 1, name: "Cloth", cat: ["fashion", "man", "women"] },
          { id: 2, name: "Shoes", cat: ["fashion"] },
          { id: 3, name: "hat", cat: ["man", "fashion"] }
        ];
    
        product.forEach((p) => {
          p.cat.forEach((cat) => {
            if(!categories.includes(cat)) {
              categories.push(cat)
            }
          })
        })
    
    console.log(categories) // ['fashion','man','women']