|
|
1
Tyler Roper
7 年前
最好的办法是创建一个单独的函数来完成这个任务,就像这样。。。
const arr1 = [ {color: "blue", shape: "triangle"}, {color: "red", shape: "square"}, {color: "green", shape: "circle"} ];
const arr2 = [ {color: "purple", shape: "diamond"}, {color: "yellow", shape: "square"}, {color: "orange", shape: "circle"} ];
const applyFiltersAndMap = (array) => {
return array.filter(obj => obj.color !== 'red')
.filter(obj => obj.shape !== 'circle')
.map(obj => `${obj.color} ${obj.shape}`);
};
console.log(applyFiltersAndMap(arr1));
console.log(applyFiltersAndMap(arr2));
也就是说,我知道您指定要为更复杂的逻辑保持方法独立,但是我仍然建议使用
reduce()
您可以更改方法以获取筛选器表达式和映射的列表,并将它们应用于
减少()
. 这将保持分离/干净的过滤器功能,同时在
reduce
const arr1 = [ {color: "blue", shape: "triangle"}, {color: "red", shape: "square"}, {color: "green", shape: "circle"} ];
const arr2 = [ {color: "purple", shape: "diamond"}, {color: "yellow", shape: "square"}, {color: "orange", shape: "circle"} ];
const applyFiltersAndMap = (array, filters, mapper) => {
return array.reduce((out,e) => {
if (filters.every(f => f(e))) out.push(mapper(e)); //filter and map
return out;
}, []);
};
const filters = [ //your filter functions
obj => obj.color !== 'red',
obj => obj.shape !== 'circle'
];
const mapper = obj => `${obj.color} ${obj.shape}`; //your map function
console.log(applyFiltersAndMap(arr1, filters, mapper));
console.log(applyFiltersAndMap(arr2, filters, mapper));
如果你不介意的话
extending
Array.prototype
...
const arr1 = [ {color: "blue", shape: "triangle"}, {color: "red", shape: "square"}, {color: "green", shape: "circle"} ];
const arr2 = [ {color: "purple", shape: "diamond"}, {color: "yellow", shape: "square"}, {color: "orange", shape: "circle"} ];
Array.prototype.applyFiltersAndMap = function(filters, mapper) {
return this.reduce((out,e) => {
if (filters.every(f => f(e))) out.push(mapper(e)); //filter and map
return out;
}, []);
};
const filters = [ //your filter functions
obj => obj.color !== 'red',
obj => obj.shape !== 'circle'
];
const mapper = obj => `${obj.color} ${obj.shape}`; //your map function
console.log(arr1.applyFiltersAndMap(filters, mapper));
console.log(arr2.applyFiltersAndMap(filters, mapper));
|