我正在尝试从数组内部和对象内部的数组中检索所有唯一值
var items = [
{
colors:['white', 'black'],
fruits:['apple, banana']
},
{
colors:['yellow', 'black'],
fruits:['mango, blueberry'],
},
...
]
const property = 'colors'
const values = this.distinct(this.items.map(item => item[property].map(elem => elem))
我希望这些值返回具有每个颜色值的数组,如下所示:
['black','white','yellow']
但是它不起作用,我也不知道为什么
答案 0 :(得分:2)
flatMap
对象数组,以提取每个colors
子数组,传递给Set构造函数以进行重复数据删除,然后将Set返回为数组:
var items = [{
colors:['white', 'black'],
fruits:['apple, banana']
},{
colors:['yellow', 'black'],
fruits:['mango, blueberry'],
}];
const colorsSet = new Set(
items.flatMap(item => item.colors)
);
const uniques = [...colorsSet];
console.log(uniques);
答案 1 :(得分:1)
reduce
可用于遍历数组并将颜色分配为累加器对象的键:
const result = items.reduce((a, {colors})=> {
colors.forEach(cl => a[cl] = 1);
return a;
}, {})
console.log(Object.keys(result));
或单行方式:
Object.keys(items.reduce((a, {colors})=> (colors.forEach(cl => a[cl] = 1) , a), {}));
一个例子:
let items = [
{
colors: ['white', 'black'],
fruits: ['apple, banana']
},
{
colors: ['yellow', 'black'],
fruits: ['mango, blueberry'],
}
]
const result = items.reduce((a, {colors})=> {
colors.forEach(cl => a[cl] = 1);
return a;
},{})
console.log(Object.keys(result));
const oneLine = Object.keys(items.reduce((a, {colors})=>
(colors.forEach(cl => a[cl] = 1) , a), {}));
console.log(oneLine);