簡體   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