gpt4 book ai didi

javascript - 具有类别的项目数组到具有项目的类别

转载 作者:行者123 更新时间:2023-12-03 06:44:05 24 4
gpt4 key购买 nike

如何将带有类别的项目数组转换为以项目为对象的类别?

输入项目数组

var items = [
{
itemId: 111111,
title: 'Item-1',
sellerName: 'seller-1',
category: 'Electronics, Fitness'
},
{
itemId: 222222,
title: 'Item-2',
sellerName: 'seller-2',
category: 'Cars'
},
{
itemId: 333333,
title: 'Item-3',
sellerName: 'seller-3',
category: 'Electronics'
},
{
itemId: 444444,
title: 'Item-4',
sellerName: 'seller-4',
category: 'Cars, Bikes'
}

]

//Result
var result = {
Electronics: [
{
itemId: 111111,
title: 'Item-1',
sellerName: 'seller-1'
},
{
itemId: 333333,
title: 'Item-3',
sellerName: 'seller-3'
}
],
Cars: [
{
itemId: 222222,
title: 'Item-2',
sellerName: 'seller-2'
},
{
itemId: 444444,
title: 'Item-4',
sellerName: 'seller-4'
}
],
Bikes: [
{
itemId: 444444,
title: 'Item-4',
sellerName: 'seller-4'
}
],

Fitness: [
{
itemId: 111111,
title: 'Item-1',
sellerName: 'seller-1'
}
]
}

我尝试了这段代码,但没有以我想要的格式给出确切的结果:

function convertItemsToCategories(items){
var categories = {};
var itemarr = [];
for(var i =0; i < items.length; i++){
//categories.push(items[i].category.split(','));
var singleCategory = items[i].category.split(',');
//categories[items[i].category] = items[i];
singleCategory.forEach(function(catname){
if(catname == items[i].category)
itemarr.push(items[i]);
categories[catname] = itemarr;
});

console.log(singleCategory);
}

console.log(categories);
}

convertItemsToCategories(items);

最佳答案

singleCategory.forEach(function(catname){
if(catname == items[i].category)
itemarr.push(items[i]);
categories[catname] = itemarr;
});

这部分代码不正确。 catname 是用“,”分隔的“类别”,category 是原始类别。而且你不断地推送 itemarr 中的项目而不清除它,所以结果非常奇怪。

请检查此jsfiddle .

关于javascript - 具有类别的项目数组到具有项目的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com