Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - 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. However I want to exclude the values which are also set with local = true in the object.

I only want ['LAJDH', 'NPSABA'] returned. 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.

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] } ] }
question from:https://stackoverflow.com/questions/65937334/using-underscore-to-filter-out-a-nested-object-and-return-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

_.reject is Underscore's negative filter function. All you need to do, is to sandwich it in between _.flatten and _.pluck. Note that this code uses an iteratee shorthand.

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

Tip: long expressions like these become more readable with _.chain.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...