简体   繁体   中英

Lodash Filter items by property value not in an array

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'
}

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);

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM