如何在javascript或lodash中删除文档数组的子集

时间:2017-05-03 22:38:56

标签: javascript lodash

我有以下对象,我想删除不属于arrayTwo的元素。我怎么能用lodash方式做到这一点。我想从ArrayOne中删除除ArrayTwo中的所有内容

ArrayOne = [
  {
    A1: {},
    B1: 'string'
  }, {
    A2: {},
    B2: 'string'
  }, {
    A3: {},
    B3: 'string'
  }, {
    A4: {},
    B4: 'string'
  }
];

ArrayTwo = [
  { A1: {} },
  { A2: {} }
]

预期结果:

ArrayOne = [
  {
    A1: {},
    B1: 'string'
  }, {
    A2: {},
    B2: 'string'                
  }
];

2 个答案:

答案 0 :(得分:2)

您可以将_.intersectionWith()_.isMatch()一起用作比较器功能:



var ArrayOne = [{"A1":{},"B1":"string"},{"A2":{},"B2":"string"},{"A3":{},"B3":"string"},{"A4":{},"B4":"string"}];

var ArrayTwo = [
  { A1: {} },
  { A2: {} }
];

var result = _.intersectionWith(ArrayOne, ArrayTwo, _.isMatch);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用嵌套循环检查ArrayOne中是否存在ArrayTne中的任何内容

&#13;
&#13;
ArrayOne = [{
  A1: {},
  B1: 'string'
}, {
  A2: {},
  B2: 'string'
}, {
  A3: {},
  B3: 'string'
}, {
  A4: {},
  B4: 'string'
}];

ArrayTwo = [{
    A1: {}
  },
  {
    A2: {}
  }
];

ArrayThree = [];
for (var i in ArrayOne) {
  loop: for (var j in ArrayTwo) {
    for (var k in ArrayTwo[j]) {
      if (JSON.stringify(ArrayOne[i][k]) == JSON.stringify(ArrayTwo[j][k])) {
        ArrayThree.push(ArrayOne[i]);
        break loop;
      }
    }
  }
}
console.log(ArrayThree);
&#13;
&#13;
&#13;