对于过滤器系统,我需要比较两个对象/数组,这是一组粗略的数据:
var books = [{
'title': 'book a',
'relatedIds': [1, 2],
'authorId': 1,
},{
'title': 'book b',
'relatedIds': [1, 2, 3, 4],
'authorId': 2,
},{
'title': 'book a',
'relatedIds': [1],
'authorId': 3,
}];
var filters = {
'relatedIds' : [1, 2, 3],
'author': [1, 2]
};
对于上述过滤器,我期望看到book a
(具有与过滤器相关的ID 1和2和作者ID 1)和book b
(具有与ID 1、2和3相关的ID和作者ID) 2(来自过滤器)。
我不希望看到book c
,因为它具有正确的相关ID,但其作者为3,但不在过滤器中。
我尝试使用lodash的过滤器方法
_.filter(books, (book) => {
....
但是我看不到如何根据从过滤器到书上的数组或int / string的数组进行比较。
答案 0 :(得分:1)
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter({initialState}) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
用于仅从原始数据中获取所需的输出filter
用于检查some
的{{1}}中是否有任何relatedId
元素filters
用于检查数组中给定值是否可用。
relativeId
答案 1 :(得分:1)
使用_.intesection()
通过检查结果的长度(如果没有相似项,则为0)在relatedIds
中查找相似项。使用_.includes()
检查authorId
是否在过滤器的author
数组中:
const books = [{"title":"book a","relatedIds":[1,2],"authorId":1},{"title":"book b","relatedIds":[1,2,3,4],"authorId":2},{"title":"book a","relatedIds":[1],"authorId":3}];
const filters = {"relatedIds":[1,2,3],"author":[1,2]};
const result = _.filter(books, o =>
_.intersection(o.relatedIds, filters.relatedIds).length &&
_.includes(filters.author, o.authorId)
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>