在Ionic 4(角度)中,我想为商品的每个唯一“类型”属性创建一个div,并在该div下添加所有具有相同“类型”的元素。
例如,我要输出以下数组:
items = [
{
type: 'type1',
question: 'question1',
answer: 'answer1'
},
{
type: 'type2',
question: 'question2',
answer: 'answer2'
},
{
type: 'type2',
question: 'question3',
answer: 'answer3'
},
{
type: 'type3',
question: 'question4',
answer: 'answer4'
},
];
是这样的:
<div id="type1">
<div class="item">
<h1>question1</h1>
<div>answer1</div>
</div>
</div>
<div id="type2">
<div class="item">
<h1>question2</h1>
<div>answer2</div>
</div>
<div class="item">
<h1>question3</h1>
<div>answer3</div>
</div>
</div>
<div id="type3">
<div class="item">
<h1>question4</h1>
<div>answer4</div>
</div>
</div>
答案 0 :(得分:2)
首先,您应该按类型对数据进行分组:
groupByType(array){
return array.reduce((r, a) => {
r[a.type] = r[a.type] || [];
r[a.type].push(a);
return r;
}, Object.create(null));
}
然后尝试使用键值管道显示您的数据:
<div *ngFor="let item of newItems | keyvalue">
<div id="{{item.key}}">
{{item.key}}
<div class="item" *ngFor="let value of item.value">
<div>{{value.question}}</div>
<div>{{value.answer}}</div>
<br>
</div>
</div>
</div>
选中DEMO。
答案 1 :(得分:1)
您可以使用此:
groupBy(list, property) {
return list.reduce((groups, item) => {
const val = item[property];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}