繁体   English   中英

JavaScript - 通过对象“过滤” - 最佳实践?

[英]JavaScript - "Filter" through an object - best practise?

通过对象“过滤”的最佳方法是什么? 我有一个示例对象,它看起来像:

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功能吗? 想了解这里尝试实现上述目标的最佳实践是什么?

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

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)

 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" }, ] } const filteredres=response['example-feed'].filter(obj=> obj.direction!=='IN' ) console.log(filteredres)

暂无
暂无

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

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