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