Lodash按属性值过滤不在数组中的项目

时间:2019-01-31 00:27:49

标签: javascript lodash

我有对象我使用lodash试图滤波器的阵列。最终目标是从阵列,其中一个属性的值是不是在另一个数组返回任何对象。

let inUse = ['1','2'];
let positionData = [{ 
    fieldID: '1',
    fieldName: 'Test1'
},
{ 
    fieldID: '2',
    fieldName: 'Test2'
},
{ 
    fieldID: '3',
    fieldName: 'Test3'
}]

// Only show me position data where the fieldID is not in our inUse array
const original = _.filter(positionData, item => item.fieldID.indexOf(inUse) === -1);

我使用indexOf,但我不,我使用它在这种情况下,右想尝试。

预期结果:

original = { 
 fieldID: '3',
 fieldName: 'Test3'
}

2 个答案:

答案 0 :(得分:2)

看起来您的indexOf倒退了;当前,它正在inUse内寻找item.fieldID

尝试一下:

const original = _.filter(positionData, item => inUse.indexOf(item.fieldID) === -1);

答案 1 :(得分:0)

您可以使用_.differenceWith()

const inUse = ['1','2'];
const positionData = [{"fieldID":"1","fieldName":"Test1"},{"fieldID":"2","fieldName":"Test2"},{"fieldID":"3","fieldName":"Test3"}];

const result = _.differenceWith(
  positionData, 
  inUse, 
  ({ fieldID }, id) => id === fieldID
);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>