3 回答
TA贡献1898条经验 获得超8个赞
const tagA = {color: ['red', 'green'],type: {a: 10,b: 7}}
const tagB = {color: ['blue', 'red'],type: {b: 54,z: 10}}
const tagC = {color: ['red', 'green', 'yellow'],type: {a: 13,b: 17}}
const tags = [tagA,tagB,tagC]
let colors = []
tags.forEach(t=>t.color.forEach(c=>colors.push(c)))
colors = colors.filter((c,i)=>colors.indexOf(c)===i)
let Color = {}
colors.forEach(c=>Color[c]=tags.filter(t=>t.color.includes(c)))
console.log(Color)
TA贡献2011条经验 获得超2个赞
你可以有像下面这样的功能getColorFilter
。详细了解Object.entries()
, flatMap
& reduce
。
注意您需要传递object
为getColorFilter({ tagA, tagB, tagC });
. 或者您可以创建新对象let obj = { tagA, tagB, tagC };
,例如getColorFilter(obj);
function getColorFilter(tags) {
return Object.entries(tags)
.flatMap(([key, val]) => val.color.map(c => ({ tag: key, color: c })))
.reduce((acc, x) => {
acc[x.color] = acc[x.color] || [];
acc[x.color].push(x.tag);
return acc;
}, {})
}
const tagA = {
color: ['red', 'green']
};
const tagB = {
color: ['blue', 'red']
};
const tagC = {
color: ['red', 'green', 'yellow']
};
const colorFilter = getColorFilter({ tagA, tagB, tagC });
console.log(colorFilter);
TA贡献1864条经验 获得超6个赞
const tagA = {
color: ['red', 'green'],
type: {
a: 10,
b: 7
}
};
const tagB = {
color: ['blue', 'red'],
type: {
b: 54,
z: 10
}
};
const tagC = {
color: ['red', 'green', 'yellow'],
type: {
a: 13,
b: 17
}
};
const tags = {
tagA: tagA,
tagB: tagB,
tagC: tagC
};
let tagsTest = Object.keys(tags);
let colorFilter = {};
tagsTest.forEach(t => {
tags[t].color.forEach(l => {
if (colorFilter.hasOwnProperty(l)) {
colorFilter[l].push(t);
}
else {
colorFilter[l] = [t];
}
}
)
});
console.log(colorFilter);
const tagA = {
color: ['red', 'green'],
type: {
a: 10,
b: 7
}
};
const tagB = {
color: ['blue', 'red'],
type: {
b: 54,
z: 10
}
};
const tagC = {
color: ['red', 'green', 'yellow'],
type: {
a: 13,
b: 17
}
};
const tags = {
tagA: tagA,
tagB: tagB,
tagC: tagC
};
let tagsTest = Object.keys(tags);
let colorFilter = {};
tagsTest.forEach(t => {
tags[t].color.forEach(l => {
if (colorFilter.hasOwnProperty(l)) {
colorFilter[l].push(t);
}
else {
colorFilter[l] = [t];
}
}
)
});
console.log(colorFilter);
Run code snippetHide resultsExpand snippet
我想我能够通过上述方法解决它。如果有更简单的方法请告诉我。
添加回答
举报