YuriGor / deepdash

eachDeep, filterDeep, findDeep, someDeep, omitDeep, pickDeep, keysDeep etc.. Tree traversal library written in Underscore/Lodash fashion
https://deepdash.io/
MIT License
274 stars 12 forks source link

Ability to retain full objects in deepFilter for arrays #38

Closed ventralnet closed 4 years ago

ventralnet commented 4 years ago

deepFilter will 'trim' the objects it filters removing parent keys that don't have children matching your predicate function. I wanted to propose the option to retain the full objects that have children that match your predicate function. So for example

const myList = [ { a: {b: 'hello'}, c: 'world' } ];
const filtered = deepFilter(myList, (value) => { return `${value}`.includes('world') };
// filtered is [ { a: {b: 'hello'}, c: 'world' } ]
// rather than [ {c: 'world' } ];
ventralnet commented 4 years ago

Or, perhaps a 'deepFind' method

YuriGor commented 4 years ago

Hi, @ventralnet, thank you for the proposal! filterDeep has keepIfEmpty option You can control do you want to keep or remove "empty" parents in case of your predicate marked the parent itself as true/undefined/false. BTW I found a bug related to this option, so thank you again ) As soon as I will fix it - I'll give you an example for your case.

YuriGor commented 4 years ago

Or maybe I didn't get your idea?

Looks like you want not to keep empty parents, but whole parents with found something inside?

There is another option: childrenPath If specified - the source object is treated as a tree with known field name for children collection. But it will work with a regular structure only.

well, let me see if it's possible with current filterDeep implementation.

YuriGor commented 4 years ago

Here is an example of filterDeep usage for such case:

var d = [ 
  { a: {b: 'hello'}, c: 'world' }, 
  { someOther: 'object',it:{should:{be:{removed:'?'}}}}, 
  {deeper:{example:{of:['hello','world']}, not:'this'}}
];
f = _.filterDeep(d, v => _.includes(v,'world') ? true : undefined,{leavesOnly:false});
console.log(f);
[
  {
    "a": {
      "b": "hello"
    },
    "c": "world"
  },
  {
    "deeper": {
      "example": {
        "of": [
          "hello",
          "world"
        ]
      }
    }
  }
]
ventralnet commented 4 years ago

@YuriGor looks good. leavesOnly is what I was looking for, thanks

YuriGor commented 4 years ago

Welcome and consider putting a star on this project :)