首页 > 解决方案 > JavaScript - 通过对象“过滤” - 最佳实践?

问题描述

通过对象“过滤”的最佳方法是什么?我有一个示例对象,如下所示:

const response = {
       "example-feed": [
          {
             "money": {
                "amount": 2588
             },
             "sourcemoney": {
                "amount": 2588
             },
             "direction": "OUT"

          },
          {
             "money": {
                "amount": 2925
             },
             "sourcemoney": {
                "amount": 2925
             },
             "direction": "IN"

          },
          {
             "money": {
                "amount": 1921
             },
             "sourcemoney": {
                "amount": 1921
             },
             "direction": "OUT"
          },
          {
             "money": {
                "amount": 1467
             },
             "sourcemoney": {
                "amount": 1467
             },
             "direction": "IN"
          },
       ]
    }

通过它“过滤”以删除任何具有键值对的对象的最佳方法是什么"direction": "IN"

例如,我想删除方向设置为 IN 的两个对象,因此新对象变为:

const response = {
   "example-feed": [
      {
         "money": {
            "amount": 2588
         },
         "sourcemoney": {
            "amount": 2588
         },
         "direction": "OUT"

      },
      {
         "money": {
            "amount": 1921
         },
         "sourcemoney": {
            "amount": 1921
         },
         "direction": "OUT"
      },
   ]
}

在一个数组中,我知道你可以使用该filter功能吗?想知道尝试实现上述目标的最佳实践是什么?

标签: javascriptarraysjson

解决方案


最佳实践是使用旨在进行过滤的方法:

response['example-feed'] = response['example-feed'].filter(f => f.direction != 'IN');

filter方法适用于数组,因此您需要过滤数组,而不是对象。

一个例子:

const response = {
    "example-feed": [
       {
          "money": {
             "amount": 2588
          },
          "sourcemoney": {
             "amount": 2588
          },
          "direction": "OUT"

       },
       {
          "money": {
             "amount": 2925
          },
          "sourcemoney": {
             "amount": 2925
          },
          "direction": "IN"

       },
       {
          "money": {
             "amount": 1921
          },
          "sourcemoney": {
             "amount": 1921
          },
          "direction": "OUT"
       },
       {
          "money": {
             "amount": 1467
          },
          "sourcemoney": {
             "amount": 1467
          },
          "direction": "IN"
       },
    ]
 };

 response['example-feed'] = response['example-feed'].filter(f => f.direction != 
 'IN');
 console.log(response)


推荐阅读