3 回答
TA贡献1829条经验 获得超7个赞
您可以对数组进行后期处理并过滤虚假值。
const cars = [{ name: "Toyota", model: "Corolla" }, { name: "Toyota", model: "Supra" }, { name: "Toyota", model: "Rav4" }, { name: "Toyota" }];
const distinctModels = [...new Set(cars.map(car => car.model))].filter(Boolean);
console.log(distinctModels);
TA贡献1798条经验 获得超7个赞
使用.hasOwnProperty来检查,如果财产的对象或不存在
const cars = [{
"name": "Toyota",
"model": "Corolla"
},
{
"name": "Toyota",
"model": "Supra"
},
{
"name": "Toyota",
"model": "Rav4"
},
{
"name": "Toyota"
}
];
const distinctModels = []
cars.forEach(function(e){
e.hasOwnProperty('model')?distinctModels.push(e.model):false;
});
console.log(distinctModels);
TA贡献1827条经验 获得超7个赞
您可以使用Array.prototype.flatMap在一个循环中完成它,当值不存在时返回一个空数组。
const cars = [{
"name": "Toyota",
"model": "Corolla"
},
{
"name": "Toyota",
"model": "Supra"
},
{
"name": "Toyota",
"model": "Rav4"
},
{
"name": "Toyota"
}
];
const distinctModels = [...new Set(cars.flatMap(car => car.model || []))];
console.log(distinctModels);
添加回答
举报