• 将一个数组转化为需要的格式,来自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)
    

      

  • 相关阅读:
    android获得屏幕高度和宽度
    Android中RelativeLayout各个属性的含义
    Android JNI知识简介
    Android结束进程方法
    android开发中的图片资源问题
    android framework下public.xml中添加资源问题
    I'm back
    test,exec,match,replace方法区别 正则
    fiddler抓包工具 https抓取 ios手机端抓取
    前端优化方案
  • 原文地址:https://www.cnblogs.com/samsara-yx/p/12054799.html
Copyright © 2020-2023  润新知