我想从React JS中的对象数组中删除重复的元素。我的代码如下:
let cars = [
{
id: 1,
make: "Volkswagen",
model: "Golf",
desc: "2.0 CR TDi Comfortline BMT"
}, {
id: 2,
make: "Audi",
model: "Q3",
desc: "2.0 CR TDi Comfortline BMT"
}, {
id: 3,
make: "Volkswagen",
model: "Passat CC",
desc: "2.0 CR TDi Comfortline BMT",
}, {
id: 4,
make: "Volkswagen",
model: "Golf",
desc: "1.9 TDI",
}, {
id: 5,
make: "Audi",
model: "Q5",
desc: "2.0 CR TDi Comfortline BMT",
}, {
id: 6,
make: "Volkswagen",
model: "Golf",
desc: "2.0 CR TDi",
}
]
class Test extends React.Component {
getTotalModels(model){
return cars.filter(c => c.model === model).length;
}
getTotalMakes(make){
return cars.filter(c => c.make === make).length;
}
render(){
return (
<div>
{cars.map(c => {
return (
<div key={c.id}>
<div className="make">{c.make} ({this.getTotalMakes(c.make)})</div>
{cars.filter(j => j.make === c.make).map(i => {
return <div className="models">{i.model} ({this.getTotalModels(i.model)})</div>
})}
</div>
)
})}
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
我得到的结果是:
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
Audi (2)
Q3 (1)
Q5 (1)
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
Audi (2)
Q3 (1)
Q5 (1)
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
我想要的结果是:
Volkswagen (4)
Golf (3)
Passat CC (1)
Audi (2)
Q3 (1)
Q5 (1)
我尝试使用
lodash uniq
函数,但是没有用。Here is a fiddle.
最佳答案
基于Lodash的解决方案,基于汽车制造商使用uniq:
class Test extends React.Component {
getTotalModels(model){
return cars.filter(c => c.model === model).length;
}
getTotalMakes(make){
return cars.filter(c => c.make === make).length;
}
render(){
return (
<div>
{
_.uniq(cars, car => car.make)
.map(c => {
return (
<div key={c.id}>
<div className="make">{c.make} ({this.getTotalMakes(c.make)})</div>
{_.uniq(cars.filter(j => j.make === c.make), car => car.model).map((make, i) => {
return <div key={i} className="models">{make.model} ({this.getTotalModels(make.model)})</div>
})}
</div>
)
})}
</div>
)
}
}
Fiddle
关于javascript - 从对象数组中获取唯一元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41183415/