我有两个数组,它们包含相同类型的对象(相同的属性,但关联的值不同)。我想比较两个数组,并匹配除一个属性外相等的对象。然后,我想在第一个数组中找到匹配对象的索引,以便将这些对象推入另一个数组中。
我认为所有这些都可以使用lodash来完成,我想避免使用for循环,以使其尽可能高效
请注意,我在js类中工作
这是我的尝试(无效)
class MatchPlayers {
constructor(){
this.TeamA = [
{weight:'75',height:'170', foot:'Left', available:true},
{weight:'88',height:'190', foot:'Right', available:true},
{weight:'65',height:'163', foot:'Right', available:false},
{weight:'70',height:'168', foot:'Left', available:true}
]
this.TeamB = [
{weight:'75',height:'170', foot:'', available:true},
{weight:'93',height:'201', foot:'', available:true},
{weight:'65',height:'163', foot:'', available:false}
]
this.MatchedPlayers = []
}
PlayersMatch (){
for(this.i=0;this.i<this.TeamA.length;this.i++){
if (_.intersection(this.TeamA,{weight:this.TeamB.weight, height:this.TeamB.height, available:this.TeamB.available})){
this.position = _.findIndex(this.TeamA,{weight:this.TeamB.weight, height:this.TeamB.height, available:this.TeamB.available})
this.MatchedPlayers.push(this.TeamA[this.position])
} else {console.log('No matchable players')}
}
console.log(this.MatchedPlayers)
}
}
在这种情况下,我想匹配除“ foot”外具有相同属性的对象,因此预期输出为:
//Expected Output:
this.MatchedPlayers = [
{weight:'75',height:'170', foot:'Left', available:true},
{weight:'65',height:'163', foot:'Right', available:false}
]
您可以采用简化的方法并忽略foot
属性,并获得_.isEqual
lefot与属性的交点。
var a = [{ weight: '75', height: '170', foot: 'Left', available: true }, { weight: '88', height: '190', foot: 'Right', available: true }, { weight: '65', height: '163', foot: 'Right', available: false }, { weight: '70', height: '168', foot: 'Left', available: true }],
b = [{ weight: '75', height: '170', foot: '', available: true }, { weight: '93', height: '201', foot: '', available: true }, { weight: '65', height: '163', foot: '', available: false }],
omitFoot = o => _.omit(o, 'foot'),
intersection = _.intersectionWith(
_.map(a, omitFoot),
_.map(b, omitFoot),
_.isEqual
);
console.log(intersection);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句