Javascript 使用下划线合并两个JS数组
我有两个JSON对象数组:Javascript 使用下划线合并两个JS数组,javascript,underscore.js,unique,Javascript,Underscore.js,Unique,我有两个JSON对象数组: Array1: [ {userId:"123",....},{userId:"124",...},....etc] 及 我想使用类似下划线的_uniq方法,但我需要消除基于userId的重复项,但我想保持对象的原样 我试过了 var coll3 = _.uniq(_.union(coll2, coll), false, function(item, key, userId){ return item.userId; }); 但我只从数组中获取用户ID
Array1: [ {userId:"123",....},{userId:"124",...},....etc]
及
我想使用类似下划线的_uniq方法,但我需要消除基于userId的重复项,但我想保持对象的原样
我试过了
var coll3 = _.uniq(_.union(coll2, coll), false, function(item, key, userId){
return item.userId;
});
但我只从数组中获取用户ID
有没有一种方法可以消除基于userId属性的重复对象,但保持其他对象不变?JSON是一种字符串表示法。你有JS数组/对象,而不是JSON。这很好用。如果
a=[{userId:123,bawd:3},{userId:124,dda:5}];b=[{userId:“125”,awd:5},{userId:“124}]
然后.uniq({u.union(a,b),false,function(item){return item.userId})
返回“[{userId:“123”,“bawd:”3},{“userId:”124”,“dda:”5},{“userId:”125”,“awd:”5}]”
那么问题出在哪里呢?你的.uniq
工作正常,但我可能会使用concat
而不是.union
:谢谢你的帮助,代码很好,但出于某种原因,userId属性位于我的对象中的另一个attributes对象中。我刚改为item.attributes.userId,它就成功了。还有,谢谢康卡特的主意,我用过了。
var coll3 = _.uniq(_.union(coll2, coll), false, function(item, key, userId){
return item.userId;
});