我有两种布局方案和一组数据。这是原始数据:
var shape = [
{ name: "fruit", value: 'apple' },
{ name: "fruit", value: 'orange' },
{ name: "rootVegetable", value: 'turnip' },
{ name: "rootVegetable", value: 'carrot' },
{ name: "vegetable", value: 'cabbage' },
{ name: "vegetable", value: 'potato' }
];
这就是我想要的样子:
var shape2 = [
[
{ name: "fruit", value: 'apple' },
{ name: "rootVegetable", value: 'turnip' },
{ name: "vegetable", value: 'cabbage' },
],
[
{ name: "fruit", value: 'orange' },
{ name: "rootVegetable", value: 'carrot' },
{ name: "vegetable", value: 'potato' },
]
]
然后我可以从中渲染一个表:
| Fruit | Root vegetable | Vegetables |
| ------ | -------------- | ---------- |
| apple | turnip | cabbage |
| orange | carrot | potato |
我知道这是reduce
的情况,但我不太清楚。
您可以尝试这个。
var shape = [
{ name: "fruit", value: 'apple' },
{ name: "fruit", value: 'orange' },
{ name: "rootVegetable", value: 'turnip' },
{ name: "rootVegetable", value: 'carrot' },
{ name: "vegetable", value: 'cabbage' },
{ name: "vegetable", value: 'potato' }
];
function getResult(shape) {
var fruits = [];
var rootVegetable = [];
var vegetable = [];
var result = [];
shape.forEach(s => {
if (s.name == "fruit")
fruits.push(s);
else if (s.name == "rootVegetable")
rootVegetable.push(s);
else if (s.name == "vegetable")
vegetable.push(s);
})
fruits.forEach((item, idx) => {
var smallArray = [];
smallArray.push(item)
smallArray.push(rootVegetable[idx]);
smallArray.push(vegetable[idx]);
result.push(smallArray);
})
return result;
}
console.log(getResult(shape));