我有一系列对象,我想获得具有相同ID的汽车的名称,并显示他们的姓名和年份:
ferrai 01-02-2000,10-23-2010
lambo 08-12-2018,02-02-2012
不喜欢这样:
ferrai 01-02-2000
ferrai 10-23-2010
lambo 08-12-2018
lambo 02-02-2012
private void btnPlayMouseReleased(java.awt.event.MouseEvent evt) {
btnPlay.setIcon(unpressPlay);
// Goes to ChoiceFrame
ChoiceFrame displayPick = new ChoiceFrame();
// Makes GameFrame visible
displayPick.setVisible(true);
// Close the previous window
//callPlay();
dispose();
}
我怎么能在angular2 +中做到这一点? 我试过这段代码:
.html文件
cars = [
[0] : { year: "01-02-2000"
sport:{id: "1111", name: "ferrai"}
}
[1] : { year: "10-23-2010"
sport:{id: "1111", name: "ferrari"}
}
[2] : {year: "08-12-2018"
sport:{id: "2222", name: "lambo"}
}
[3] : {year: "02-02-2012"
sport:{id: "2222", name: "lambo"}
}
]
.ts文件
<div *ngFor="let obj of cars">
<div *ngFor="let name of obj.sport">
<div>{{getCars(name)}}</div>
</div>
</div>
我感谢任何帮助!
答案 0 :(得分:1)
我个人会按摩&#34;在让DOM渲染之前,数据首先出现。我个人喜欢对数据做很多工作(在服务器端或在它到达某个DOM迭代器之前构建元素之前),以便视图可以尽可能简单。这就是我要做的事情(修正了一个错字,这是 vanilla javascript ):
cars = [
{
year: "01-02-2000",
sport:{id: "1111", name: "ferrari"}
},
{
year: "10-23-2010",
sport:{id: "1111", name: "ferrari"}
},
{
year: "08-12-2018",
sport:{id: "2222", name: "lambo"}
},
{
year: "02-02-2012",
sport:{id: "2222", name: "lambo"}
}
]
newCarsData = cars.reduce((acc, curr) => {
if (!acc.hasOwnProperty(curr.sport.name)) {
acc[curr.sport.name] = {};
acc[curr.sport.name].years = []
}
acc[curr.sport.name].years.push(curr.year);
return acc;
}, {});
console.log(newCarsData);
现在您将拥有此数据结构:
{
ferrari: {
years: [ '01-02-2000', '10-23-2010' ]
},
lambo: {
years: [ '08-12-2018', '02-02-2012' ]
}
}
并且在角度或任何框架中重复都很容易
答案 1 :(得分:1)
使用reduce的答案很漂亮,我建议学习该解决方案,因为.reduce是原生JS中最强大,最通用的方法之一。
这是一个更普通的解决方案,不使用高阶函数:
var cars = [
{
year: "01-02-2000",
sport:{id: "1111", name: "ferrari"}
},
{
year: "10-23-2010",
sport:{id: "1111", name: "ferrari"}
},
{
year: "08-12-2018",
sport:{id: "2222", name: "lambo"}
},
{
year: "02-02-2012",
sport:{id: "2222", name: "lambo"}
}
]
function simplifyInventory(cars) {
var objList = {};
for (var i = 0; i < cars.length; i++) {
if (objList.hasOwnProperty(cars[i].sport.name) === false) {
objList[cars[i].sport.name] = [cars[i].year];
} else {
objList[cars[i].sport.name].push(cars[i].year)
}
}
return objList;
}
console.log(simplifyInventory(cars));
=====console=====
{ ferrari: [ '01-02-2000', '10-23-2010' ], lambo: [ '08-12-2018', '02-02-2012' ] }
然后你可以很容易地把它变成几乎任何形式。