我有1个对象数组(名为childrenArray),如下所示:
[
{name:'somevalue',favColors:['red','purple','green']},
{name:'somevalue1',favColors:['blue','brown','pink]},
{name:'somevalue2',favColors:['orange','yellow']}
]
还有一个具有以下属性的对象:
{colorBook:'somevalue4', colors:['red','blue']}
基本上,我想过滤对象数组以返回与我的对象具有共同颜色属性的对象。
因此,搜索colors属性将导致
{name:'somevalue',favColors:['red','purple','green']},
{name:'somevalue1',favColors:['blue','brown','pink]},
到目前为止,我已经尝试过:
getElementsByColors(colors: string[]){
return _.filter(this.childrenArray, function(child) {
child.favColors.find( color => color === colors.forEach(c => c)}
答案 0 :(得分:0)
您可以通过childrenArray
检查Array.some()
来过滤Array.includes()
是否包含至少一种颜色(或所有颜色中的每一种)和const childrenArray = [
{name:'somevalue',favColors:['red','purple','green']},
{name:'somevalue1',favColors:['blue','brown','pink']},
{name:'somevalue2',favColors:['orange','yellow']}
]
const getElementsByColors = ({ colors }) =>
childrenArray.filter(({ favColors }) =>
colors.some(color => favColors.includes(color)) // or every for all of them
)
const result = getElementsByColors({colorBook:'somevalue4', colors:['red','blue']})
console.log(result)
:
cube(int(num1))
答案 1 :(得分:0)
在lodash中,这与.some , .filter和_.includes的使用非常相似:
const data = [ {name:'somevalue',favColors:['red','purple','green']}, {name:'somevalue1',favColors:['blue','brown','pink']}, {name:'somevalue2',favColors:['orange','purple', 'green']} ]
const filter1 = {colorBook:'somevalue4', colors:['red','blue']}
const filter2 = {colorBook:'somevalue4', colors:['purple','green']}
let matchSomeColors = (d, f) =>
_.filter(d, ({favColors}) => _.some(f.colors, c => _.includes(favColors, c)))
let matchEveryColor = (d, f) =>
_.filter(d, ({favColors}) => _.every(f.colors, c => _.includes(favColors, c)))
console.log('some: ', matchSomeColors(data, filter1))
console.log('every: ', matchEveryColor(data, filter2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
我还添加了_.every,因此您可以看到其中的区别。但是,如果只需要为此使用lodash,那么最好只使用普通的JS等。