有没有一种方法可以只选择彼此不同的对象数组的属性



假设我有这个对象数组。

let cars = [
{
color: "purple",
type: "minivan",
capacity: 7
},  
{
color: "purple",
type: "ferrari",
capacity: 3
},
{
color: "green",
type: "bike",
capacity: 1
}

有没有一种方法可以只获得值";紫色";以及";绿色";在一个数组中一次而不重复?

也许这就是您想要的

const colors = cars.map(car => car.color);
const unique = [...new Set(colors)];

试试这个:

let cars = [
{
color: "purple",
type: "minivan",
capacity: 7
},  
{
color: "purple",
type: "ferrari",
capacity: 3
},
{
color: "green",
type: "bike",
capacity: 1
}
]
let colors = [];
cars.forEach(car => {
if(!(colors.includes(car.color))) colors.push(car.color);
});
console.log(colors);

如果您需要整个car,那么只需按下car而不是car.color

var _ = require("lodash");
const cars = [
{
color: "purple",
type: "minivan",
capacity: 7
},  
{
color: "purple",
type: "ferrari",
capacity: 3
},
{
color: "green",
type: "bike",
capacity: 1
}
]
_.uniqBy(cars, 'color')
// Array (2 items)
// 0: Object {capacity: 7, color: "purple" , type: "minivan"}
// 1: Object {capacity: 1, color: "green" , type: "bike"}

相关内容

  • 没有找到相关文章

最新更新