我有一个颜色数组和一个对象数组。每个对象都包含自己的颜色数组。
颜色数组:
colors = [
'yellow',
'blue',
'red',
'green',
'purple',
'brown',
'fuscia',
'grey',
'beige',
'orange',
]
对象数组:
paintings = [{
name: 'The Wind',
rating: '25',
colors: [
'orange',
'blue',
]
},
{
name: 'The Sons',
rating: '8',
colors: [
'red',
'green',
'yellow',
]
},
{
name: 'Freedom',
rating: '16',
colors: [
'grey',
'yellow',
]
},
{
name: 'Space',
rating: '50',
colors: [
'purple',
'green',
'orange',
]
}
]
我在这里想要实现的目标是使颜色数组中的每种颜色本身成为一个数组,并且每个新的颜色数组将包含其自己的颜色数组中包含该颜色的绘画对象。此外,这些对象中的每一个都将从最高评级到最低评级排序。我需要得到这样的结果:
yellow = [{
name: 'Freedom',
rating: '16',
colors: [
'grey',
'yellow',
]
},
{
name: 'The Sons',
rating: '8',
colors: [
'red',
'green',
'yellow',
]
}
]
green = [{
name: 'Space',
rating: '50',
colors: [
'purple',
'green',
'orange',
]
} {
name: 'The Sons',
rating: '8',
colors: [
'red',
'green',
'yellow',
]
}]
orange = [{
name: 'Space',
rating: '50',
colors: [
'purple',
'green',
'orange',
]
} {
name: 'The Wind',
rating: '25',
colors: [
'orange',
'blue',
]
}]
等等...
上面的数据显然是虚拟数据。我实际上正在循环一个非常大的数组。我通过循环对象提取了颜色数组,使用 flat()
展平数组并使用 Set()
创建一个新的颜色数组,这样我就可以有一个列表要在每个对象中查找的颜色。
那么,如何才能以最有效的方式实现上述目标呢?
解决方案的附加信息:
按照以下方式对原始数据进行排序后,我最终对数组进行了分组:
paintings.forEach((i) => {
paintings.sort((a, b) => b.rating - a.rating)
})
const colorGroup = colors.map((color) => ({
[color]: paintings
.filter((painting) => painting.colors.includes(color))
}));
然后我限制只显示 vue-for
循环中的 25 个:
<div v-for="painting in colorGroup.slice(0, 25)">
{{ painting }}
</div>
感谢您的帮助!
最佳答案
试试这个。
var paintings = [{
name: 'The Wind',
rating: '25',
colors: [
'orange',
'blue',
]
},
{
name: 'The Sons',
rating: '8',
colors: [
'red',
'green',
'yellow',
]
},
{
name: 'Freedom',
rating: '16',
colors: [
'grey',
'yellow',
]
},
{
name: 'Space',
rating: '50',
colors: [
'purple',
'green',
'orange',
]
}
];
var colors = [
'yellow',
'blue',
'red',
'green',
'purple',
'brown',
'fuscia',
'grey',
'beige',
'orange',
];
const colorObj = colors.map((color) => ({
[color]: paintings.filter((painting) => painting.colors.includes(color)).sort((a, b) => b.rating - a.rating)
}));
console.log(colorObj);
关于arrays - Javascript 列出数组中包含嵌套数组中的值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63097027/