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

deepMap can alter structure? #37

Closed masciugo closed 3 years ago

masciugo commented 4 years ago

I used deep map to integrate some object node with extra properties and deepMap works perfectly returning new value where I want. The structure of the mapped object remains the same.

Let's suppose I need to transform array of strings node in a leaf with those string concatenated altering the structure:

{ arr: ['a', 'b', { c: ['y', 'w', 'z'] }, 'd', 'e'] }

{ arr: ['a', 'b', { c: "ywz" }, 'd', 'e'] }

I was no able to do that with deepMap. Is it possible?

YuriGor commented 4 years ago

Probably i will need to enhance mapDeep, right now it's possible to do with eachDeep, but i am out of my laptop, so i will be able to create an example only in some hours.

YuriGor commented 4 years ago

I hope I understood your criteria right: you want to replace any flat array by CSV string? here is an example:

var data = { arr: ['a', 'b', { c: ['y', 'w', 'z'] }, 'd', 'e',[1,2,3],{more:{nested:{arrays:[[1,2,3],[4,5,6],[7,8,9]]}}}]};
_.eachDeep(data,(val, key, parent, context)=>{
  if(_.isArray(val) && !_.some(val, _.isObject)){
    parent[key] = val.join();
    return false;
  }
});

data:

{
  "arr": [
    "a",
    "b",
    {
      "c": "y,w,z"
    },
    "d",
    "e",
    "1,2,3",
    {
      "more": {
        "nested": {
          "arrays": [
            "1,2,3",
            "4,5,6",
            "7,8,9"
          ]
        }
      }
    }
  ]
}

play with demo here

YuriGor commented 4 years ago

And about topic question: "can mapDeep alter structure?" As said in docs "mapDeep returns an object with the same structure with values trasformed thru iteratee." So, no, it cannot. And I will keep it as is because it's made intentionally, to mimic the behavior of native Array.map method (And it's not cargo-cult - it really makes sense).

Let me know please, if my suggestion works for you.