zoukankan      html  css  js  c++  java
  • 将一个数组转化为需要的格式,来自react官网的商品列表示例

    //原来的格式
    const PRODUCTS = [
        { category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football' },
        { category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball' },
        { category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball' },
        { category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch' },
        { category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5' },
        { category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7' }
    ];
    //需要的格式  (就是把公共的标题提取出来了)
    const res=[{ category: 'Sporting Goods' },
    {
        product:
        {
            category: 'Sporting Goods',
            price: '$49.99',
            stocked: true,
            name: 'Football'
        }
    },
    {
        product:
        {
            category: 'Sporting Goods',
            price: '$9.99',
            stocked: true,
            name: 'Baseball'
        }
    },
    {
        product:
        {
            category: 'Sporting Goods',
            price: '$29.99',
            stocked: false,
            name: 'Basketball'
        }
    },
    { category: 'Electronics' },
    {
        product:
        {
            category: 'Electronics',
            price: '$99.99',
            stocked: true,
            name: 'iPod Touch'
        }
    },
    {
        product:
        {
            category: 'Electronics',
            price: '$399.99',
            stocked: false,
            name: 'iPhone 5'
        }
    },
    {
        product:
        {
            category: 'Electronics',
            price: '$199.99',
            stocked: true,
            name: 'Nexus 7'
        }
    }]
    
    let rows = [];
    //记录最后一个分类的值,初始值为null
    let lastCategory = null;
    PRODUCTS.forEach(item => {
        if (item.category !== lastCategory) {
            rows.push({ category: item.category })
        }
        rows.push({ product: item })
        lastCategory = item.category;
    })
    console.log(rows)
    

      

  • 相关阅读:
    C++ Primer 读书笔记 第六章
    C++ Primer 读书笔记 第十章
    面试题笔记
    C++ Primer 读书笔记 第八章
    ZedGraph源码学习(三)
    一个简单的代码生成器XML与XLST的应用测试。
    信息导到Execl上.
    SQL相关功能实现.
    ZedGraph源码学习(二)
    EXECL导入(检查服务器版本.包括NPOI方式导入.可以通过配置文件信息导入EXECL)代码记录下.
  • 原文地址:https://www.cnblogs.com/samsara-yx/p/12054799.html
Copyright © 2011-2022 走看看