检查对象值数组是否存在于另一个数组中但长度不同

时间:2016-10-30 12:46:38

标签: javascript jquery lodash

我有2个数组的对象,只想检查b中是否存在,如果是则添加新属性。但是b的长度是动态的。我将得到未定义b的错误。

var a = [{name:'john'},{name:'james'},{name:'jordan'},{name:'joe'}];
var b = [{name:'john'},{name:'joe'}];

var exist = 0;
var c = _.map(a,function(result,i){
    exist = b[i].name.indexOf(a.name) > -1 ? exist = 1 : exist = 0;

    return _.extend({},c,{'exist':exist});
});

任何线索?

3 个答案:

答案 0 :(得分:3)

我会迭代b个对象,并且每个对象检查它们是否存在于A中,如下例所示。

    var a = [ { _id: '5815adb4badf3f311a2cd25b', username: 'david&jane' },
    { _id: '5815e40e136c8e33b65b3478', username: 'david+jane' } ];
    var b = [ { username: 'david&jane' },
              { username: 'david<3jane' },
              { username: 'david+jane' },
              { username: 'davidjane' } 
    ]
    var c = [];

    b.forEach(function(user) {
      var exists = false;
      for (let i=0; i<a.length && !exists; i++){
          exists = a[i].username === user.username ;
      }
      
      c.push(Object.assign({},user,{exists}));
    });

    console.log(c);

答案 1 :(得分:1)

第一个stringify a数组。循环遍历b并创建一个动态正则表达式以在a上测试,如果测试匹配您的东西。

希望这有帮助!

&#13;
&#13;
var a = [{name:'john'},{name:'james'},{name:'jordan'},{name:'joe'}];
var b = [{name:'john'},{name:'joe'}, {name:'hello'}];

var strA = JSON.stringify(a)

var result = b.map((el) => {
  var elStr = JSON.stringify(el)
  var regex = new RegExp(elStr, 'g')
  if(regex.test(strA))
     return Object.assign({}, el, {exist: 1})
  return Object.assign({}, el, {exist: 0})
})

console.log(result)
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用Array.every检查b中的每个对象是否也在a中,并且在回调中您可以使用Array.some来检查a用于键和值

var a = [{name:'john'},{name:'james'},{name:'jordan'},{name:'joe'}];
var b = [{name:'john'},{name:'joe'}];

var exist = b.every( (o) => {
    let k = Object.keys(o)[0];
    return a.some( p => k in p && p[k] === o[k]);
});

console.log(exist)

如果你想添加属性,你也可以这样做

var a = [{name:'john'},{name:'james'},{name:'jordan'},{name:'joe'}];
var b = [{name:'john'},{name:'joe'}];

var c = b.map( (o) => {
    let k = Object.keys(o)[0];
    return o.exist = a.some( p => k in p && p[k] === o[k]), o;
});

console.log(c);