简体   繁体   English

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

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

I have a filter method that filters an item from an array using an if condition. 我有一个使用if条件从数组中过滤项目的过滤方法。 Using the filterArray I then use map method. 然后使用filterArray我使用map方法。

I would like to add a second condition and push a new array called OLD_ITEMS to the ITEMS array. 我想添加第二个条件,并将一个名为OLD_ITEMS的新数组推送到ITEMS数组。 How would I go about doing this? 我将如何去做呢?

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 }))
);

You need to be a little more clear about what you mean by "push" OLD_ITEMS to Items. 您需要更加清楚“将” OLD_ITEMS“推入项目”的含义。 Do you want to concatenate/push ALL of the OLD_ITEMS to the end of if a single condition is met, or do you want to push subset of OLD_ITEMS that meet a certain condition? 如果要满足单个条件,是否要将所有OLD_ITEMS连接/推到末尾,还是要推送满足一定条件的OLD_ITEMS的子集?

I believe that this is what you're looking for, but it's hard to know exactly: 我相信这就是您要寻找的东西,但是很难确切知道:

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 }))
);

Also, I highly recommend making your code more concise by returning the value of the conditional check, instead of an if/then 另外,我强烈建议您通过返回条件检查的值而不是if / then来使代码更简洁

let filterArray = ITEMS.filter(item => {
    return (item.id === 'three');
});

Or even more concise 甚至更简洁

let filterArray = ITEMS.filter(item => (item.id === 'three'));

Grand finale of conciseness: 简洁大结局:

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