Reputation: 8970
I have an array of objects I am trying to filter using lodash. The end goal is to return any objects from the array where the value of a property is not in another array.
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);
I tried using indexOf
but I don't think I am using it right in this situation.
Expected Result:
original = {
fieldID: '3',
fieldName: 'Test3'
}
Upvotes: 3
Views: 1925
Reputation: 191976
You can use _.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>
Upvotes: 2
Reputation: 56572
It looks like you have your indexOf
backwards; currently, it's looking for inUse
inside of item.fieldID
.
Try this:
const original = _.filter(positionData, item => inUse.indexOf(item.fieldID) === -1);
Upvotes: 3