我有一个多维数组。我想组在此的价值观和知道有多少。
我创建了一个新的阵列。我一直循环多维数组。如果当前值没有新的数组中存在,我添加此值到阵列中。但我不能这样做动态,他们都加入到了底部。我不能把它添加到“子类别”。
这样,我有一个多维数组。
currentArray = [
[1, 2, 3, 5],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
]
我用这样的循环。
newArray= [];
for (let i = 0; i < currentArray.length; i++) {
for (let k = 0; k < currentArray[i].length; k++) {
let obj = { id: currentArray[i][k], subCategories: [] };
let index = newCategories.findIndex(x => x.id === obj.id);
if (index === -1) {
if (k === 0) {
newCategories.push(obj);
}
} else {
newCategories[index].subCategories.push(obj);
}
}
}
我用这样的循环,但我没有得到一个成功的结果。在当前的代码逻辑错误,我无法弄清楚。
我想在数组中相同的元素被添加到新的阵列只有一次。我想在最后的元素得到“计数”。
所以我想实现输出如下。
{
"id": 1,
"subCategories": [
{
"id": 2,
"subCategories": [
{
"id": 3,
"subCategories": [
{
"id": 5,
"count": 1,
"subCategories": []
},
{
"id": 4,
"count": 6,
"subCategories": []
}
]
}
]
}
]
}
你可以通过减少内部阵列减少阵列和查找想要的ID。
var array = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
result = array
.reduce((r, a) => {
var o = a.reduce((p, id) => {
var temp = p.subCategories.find(q => q.id === id);
if (!temp) {
p.subCategories.push(temp = { id, subCategories: [] });
}
return temp;
}, r);
o.count = (o.count || 0) + 1;
return r;
}, { subCategories: [] })
.subCategories;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这是相同的风格,你有,通过使用内部格式和项目为下一级返回此对象的搜索匹配的起始对象。
var currentArray = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
newArray = [],
temp,
item;
for (let i = 0; i < currentArray.length; i++) {
temp = { subCategories: newArray };
for (let k = 0; k < currentArray[i].length; k++) {
item = temp.subCategories.find(x => x.id === currentArray[i][k]);
if (!item) {
temp.subCategories.push(item = { id: currentArray[i][k], subCategories: [] });
}
temp = item;
}
temp.count = (item.count || 0) + 1;
}
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }