繁体   English   中英

如何在JavaScript中将数组推送与过滤器和映射方法一起使用

[英]How to use array push with filter and map method in JavaScript

我有一个使用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 }))
);

您需要更加清楚“将” 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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