我有一个filter方法,它使用if
条件从数组中过滤出一个项目。然后使用filterArray
使用map方法。
我想添加第二个条件,并将名为OLD_ITEMS
的新数组推入ITEMS
数组。我将如何去做?
import { OLD_ITEMS, ITEMS } from './constants';
let filterArray = ITEMS.filter(item => {
if (item.id === 'three') {
return false;
}
return true;
});
// TODO: add second condition here to push `OLD_TIMES` to `ITEMS`
const options = Object.assign(
...filterArray.map(({ id, name }) => ({ [id]: name }))
);
答案 0 :(得分:0)
您需要更加清楚“将” OLD_ITEMS“推入项目”的含义。如果要满足单个条件,是否要将所有OLD_ITEMS连接/推送到末尾,还是要推送满足特定条件的OLD_ITEMS的子集?
我相信这就是您要寻找的东西,但是很难确切知道:
import { OLD_ITEMS, ITEMS } from './constants';
let filterArray = ITEMS.filter(item => {
if (item.id === 'three') {
return false;
}
return true;
});
// TODO: add second condition here to push `OLD_TIMES` to `ITEMS`
const validOldItems = OLD_ITEMS.filter(item => {
if (item === 'some_condition') {
return false;
}
return true;
}
filterArray.push(validOldItems);
const options = Object.assign(
...filterArray.map(({ id, name }) => ({ [id]: name }))
);
此外,我强烈建议您通过返回条件检查的值而不是if / then来使代码更简洁
let filterArray = ITEMS.filter(item => {
return (item.id === 'three');
});
或更简洁
let filterArray = ITEMS.filter(item => (item.id === 'three'));
简洁大结局:
const filterArray = ITEMS.filter(item => (item.id === 'three'))
.concat(OLD_ITEMS.filter(item => (item.id === 'some_condition'))
.map(({ id, name }) => ({ [id]: name }))
const options = Object.assign(...filterArray);