【问题标题】:How to Structure This array, Separate Category and Product如何构造这个数组,分离类别和产品
【发布时间】:2020-04-23 17:21:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript java arrays reactjs


    【解决方案1】:

    第一个答案:

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

    【讨论】:

    • 我看到 3 个循环来解决任务,我相信有更好的方法
    • 结果数组怎么做
    【解决方案2】:

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

    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
                        }
                    }
                })
            }
        )
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 2021-11-08
      • 1970-01-01
      相关资源
      最近更新 更多