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
我想我能夠通過上述方法解決它。如果有更簡單的方法請告訴我。
添加回答
舉報