简体   繁体   English

使用下划线过滤掉一个嵌套的 object 并返回一个数组

[英]Using underscore to filter out a nested object and return an array

const newData = _.pluck(_.flatten(_.values(file)), 'Message')

This is the correct way to return an array with all the messages values from this giant nested object, which is great.这是从这个巨大的嵌套 object 返回包含所有消息值的数组的正确方法,这很棒。 However I want to exclude the values which are also set with local = true in the object.但是我想排除在 object 中也设置为 local = true的值。

I only want ['LAJDH', 'NPSABA'] returned.我只希望 ['LAJDH', 'NPSABA'] 返回。 Essentially what I am doing is writing tests in jest which will open up thousands of files and return me an array to use.本质上,我正在做的是开玩笑地编写测试,这将打开数千个文件并返回一个数组供我使用。 I'm exporting this object to be required in each iteration in my jest test.我正在导出这个 object 在我的笑话测试中的每次迭代中都需要。

This means it would be awesome to have this executed as fast as possihle.这意味着尽可能快地执行它会很棒。

Example data:示例数据:

{ onOrder: [],
  onGo: [],
  onDelivery:
   [ { Trigger: 'Ready To Dispatch',
       Channel: 'Mail',
       Message: 'AJDSA',
       local: true
       Recipient: [Array],
       Filter: [Array] },
     { Trigger: 'Ready to Delivery',
       Channel: 'Mail',
       Message: 'LAJDH',
       Recipient: [Array],
       Filter: [Array] } ],
  onDelay:
   [ { Trigger: 'Delay',
       Channel: 'Mail',
       Message: 'ABJSH',
       local: true,
       Recipient: [Array],
       Filter: [Array] } ],
  onDelivered:
   [ { Trigger:
       'Delivered',
       Channel: 'Mail',
       Message: 'NPSABA',
       Recipient: [Array],
       Filter: [Array] } ] }

_.reject is Underscore's negative filter function. _.reject是 Underscore 的负过滤器 function。 All you need to do, is to sandwich it in between _.flatten and _.pluck .您需要做的就是将它夹在_.flatten_.pluck之间。 Note that this code uses an iteratee shorthand .请注意,此代码使用iteratee 速记

const newData = _.pluck(_.reject(_.flatten(_.values(file)), {local: true}), 'Message');

Tip: long expressions like these become more readable with _.chain .提示:像这样的长表达式使用_.chain变得更具可读性。

const newData = _.chain(file)
    .values()
    .flatten()
    .reject({local: true})
    .pluck('Message')
    .value();

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

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