简体   繁体   English

根据条件从数组中删除特定项目并返回 javascript 中的其他项目

[英]Remove a particular item from array based on condition and return other items in javascript

I have an array with objects below我有一个包含以下对象的数组

selectedOption = [
    {
            id: 'REPORTORDER',
            name: 'reportOrder'
        },
    {
            id: 'REORDER',
            name: ‘reorder'
        },
    {
            id: 'RETURNPRODUCTS',
            name: 'returnProducts'
        },
     {
            id: 'ENTERPO',
            name: 'enterPo'
        }
]

Based on a condition that if shipmentStatus is "CANCELLED" and entriesList is [] I want to remove the second item from the above array.基于shipmentStatus为“CANCELLED”且entriesList为 [] 的条件,我想从上述数组中删除第二项。

I have tried using filter method as written below:我尝试使用如下所示的过滤方法:

selectedOption.filter(item => (shipmentStatus == "CANCELLED" && entriesList == []) ? item.name != "reorder" : item.name)

If I got you right you want to mutate array based on external condition, in that case, you must check condition outside filter like this如果我没看错你想根据外部条件改变数组,在这种情况下,你必须像这样检查filter外部的条件

 let condition = true; let selectedOption = [{ id: 'REPORTORDER', name: 'reportOrder' }, { id: 'REORDER', name: 'reorder' }, { id: 'RETURNPRODUCTS', name: 'returnProducts' }, { id: 'ENTERPO', name: 'enterPo' } ]; if (condition) selectedOption = selectedOption.filter(item => item.name.= 'reorder') console.log(selectedOption)

  1. filter returns a new array, so you'll need to reassign selectedOption to the result of filter . filter返回一个新数组,因此您需要将selectedOption重新分配给filter的结果。

  2. The conditional will always fail since entriesList will never equal a new empty array.条件总是会失败,因为 entriesList 永远不会等于一个新的空数组。 It's better to check if the array is empty by comparing the length to zero.最好通过将长度与零进行比较来检查数组是否为空。

  3. It's better to check the global conditions outside the filter.最好检查过滤器外的全局条件。

if (shipmentStatus === 'CANCELLED' && Array.isArray(entriesList) && entriesList.length === 0) {
   selectedOption = selectedOption.filter(
     (item) => item.name != 'reorder'
   );
}
    const selectedOption = [
  {
    id: 'REPORTORDER',
    name: 'reportOrder',
  },
  {
    id: 'REORDER',
    name: 'reorder',
  },
  {
    id: 'RETURNPRODUCTS',
    name: 'returnProducts',
  },
  {
    id: 'ENTERPO',
    name: 'enterPo',
  }];

const shipmentStatus = 'cancelled';
const entriesList = [];

console.log(selectedOption.filter((x) => (x.name !== 'reorder') || !(shipmentStatus === 'cancelled' && !entriesList.length)));

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

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