由于您尚未提供任何工作代码,让我为您提供一些代码,我相信您将能够从那里构建您的引导程序。
您的原始数据
const data = [
{color: "green", number: 23},
{color: "red", number: 25},
{color: "green", number: 27},
{color: "green", number: 26},
{color: "orange", number: 30}
];
让我们初始化变量...
let previousItemColor = false;
let newData = [];
遍历我们的原始数据...
data.map((item, index) => {
// Does our last iteration was about the same color ? ?
// Yes ! ✨
if (item.color === previousItemColor) {
// Remove the last entry from newData and store it in lastItem
let lastItem = newData.pop();
// Append the new item into lastItem elements property
lastItem.elements.push(item)
// Push that modified entry into newData array
newData.push(lastItem);
}
// Oh! That's a new entry ?
else {
let newEntry = {
groupName: item.color,
elements: [item]
};
newData.push(newEntry);
}
// Don't forget, we need to store that color into peviousItemColor, so our script know what was the last iteration.
previousItemColor = item.color;
});
让我们检查一下我们是否走对了……
console.log(newData);
预期结果:
data = [
{groupName: "green", elements: [{color: green, number: 23}]},
{groupName: "red", elements: [{color: red, number: 25}]},
{groupName: "green", elements: [{color: green, number: 27}, {color: green, number: 26}]},
{groupName: "orange", elements: [{color: orange, number: 30}]}
];
由于我们现在有可用的数据,我们可以构建任何我们喜欢的下拉菜单...
newData.map((item, index) => {
console.log(`${item.groupName} ${(item.elements.length > 1 ? item.elements.length : '')}`);
});
预期结果:
green
red
green 2
orange
使用这种方法,您仍然可以保留一开始拥有的所有数据,以便您可以在下拉列表中创建子项。
附注我知道还有另一种方法可以解决它,但由于 O.P. 看起来很新,让我们让它走得更远,让他/她了解整个过程。