我有一个简单的数组,想要循环遍历具有相同键和值的数组,并且我想创建一组相同的值并将相关项放在其下。
export class AppComponent implements OnInit {
data = [
{
'con': 'Usa',
'city': 'ny',
'town':'as'
},
{
'con': 'Ger',
'city': 'ber',
'town':'zd'
},
{
'con': 'Usa',
'city': 'la',
'town':'ss'
}
];
array: any[] = [];
ngOnInit() {
this.array = this.data;
}
}
html:
<div *ngFor="let item of array ">
<h3>{{item.con}}</h3>
<p>{{item.city}}</p>
<p>{{item.town}}</p>
<hr>
</div>
我得到了以下结果:
Usa
ny
as
-----
Ger
ber
zd
-----
Usa
la
ss
-----
但我真正想要的是用相同的名称创建一组这些国家,并使用以下格式在该组下显示相关的城市和城镇:
[{
"con": "usa",
"area": [{
"city": "ny",
"town": "as"
}, {
"city": "la",
"town": "ss"
}]
},
{
"con": "ger",
"area": [{
"city": "ber",
"town": "zd"
}]
}
]
最佳答案
将数据转换为包含合并对象的数组,其中 cities
属性具有数组,如下所示
[
{ con: "Usa": cities: ["ny", "la"] },
{ con: "Ger", cities: ["ber"] }
]
您可以按如下方式构建该数据结构:
this.array = Array.from(
this.data.reduce(
(map, {con, city}) => map.set(con, (map.get(con) || []).concat(city)),
new Map
), ([con, cities]) => ({ con, cities })
);
那么HTML部分就变成了:
<div *ngFor="let item of array ">
<h3>{{item.con}}</h3>
<div *ngFor="let city of item.cities ">
<p>{{city}}</p>
</div>
<hr>
</div>
关于javascript - 如何创建一组相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129461/