根据店铺名字分组

根据店铺名字分组

购物车原数组
const arr = [{

    shopname: '天猫店铺',

ischeck: false,

goodsimg: '/wp-content/uploads/new2024/02/20240204vue12345/u=3447506328,3763843571&fm=26&gp=0120.jpg',

goodsname: '芳姐卤香干 600g湖南特产武冈 卤豆腐豆干制品休闲素食零...',

price: '99.50',

maxnum: 100,

num: 1

},

{

shopname: '天猫店铺',

ischeck: false,

goodsimg: '/wp-content/uploads/new2024/02/20240204vue12345/u=3447506328,3763843571&fm=26&gp=0120.jpg',

goodsname: '麻辣王子',

price: '10.50',

maxnum: 100,

num: 1

},

{shopname:"淘宝普通店铺"

ischeck: false,

goodsimg: '/wp-content/uploads/new2024/02/20240204vue12345/u=249803900,574094454&fm=11&gp=0121.jpg',

goodsname: '淘宝普通店铺商品',

price: '88.40',

maxnum: 100,

num: 1

}

]

怎么变成下面的数组
const arr1 = [

    {

shopname: '天猫店铺',

goodslist: [{

ischeck: false,

goodsimg: '/wp-content/uploads/new2024/02/20240204vue12345/u=3447506328,3763843571&fm=26&gp=0120.jpg',

goodsname: '芳姐卤香干 600g湖南特产武冈 卤豆腐豆干制品休闲素食零...',

price: '99.50',

maxnum: 100,

num: 1

},

{

ischeck: false,

goodsimg: '/wp-content/uploads/new2024/02/20240204vue12345/u=3447506328,3763843571&fm=26&gp=0120.jpg',

goodsname: '麻辣王子',

price: '10.50',

maxnum: 100,

num: 1

}

]

},

{

shopname: '淘宝普通店铺',

goodslist: [{

ischeck: false,

goodsimg: '/wp-content/uploads/new2024/02/20240204vue12345/u=249803900,574094454&fm=11&gp=0121.jpg',

goodsname: '淘宝普通店铺商品',

price: '88.40',

maxnum: 100,

num: 1

}]

}

]


回答:

function classify(arr) {

var ret = [];

loop: for (var i = 0; i < arr.length; ++i) {

var obj = {}, name = "shopname";

for (var key in arr[i]) {

if (key === name) continue;

obj[key] = arr[i][key];

}

for (var j = 0; j < ret.length; ++j) {

if (arr[i][name] === ret[j][name]) {

ret[j].goodslist.push(obj);

continue loop;

}

}

ret.push({

shopname: arr[i][name],

goodslist: [obj]

});

}

return ret;

}

console.dir(classify(arr));


回答:

let obj = {}

let res = arr.reduce((l, i) => {

if(obj[i.shopname]){

obj[i.shopname].goodslist.push(i)

}else{

l.push(obj[i.shopname] = {shopname: i.shopname, goodslist: [i]})

}

return l

}, [])


回答:

可以考虑让后端写一条sql

以上是 根据店铺名字分组 的全部内容, 来源链接: utcz.com/p/937501.html

回到顶部