简体   繁体   中英

map and deep object with Ramda

I need to filter by "segments" properties, in this case i need to filtering by segment : [name: "general]

I Have following array

const lines = [{
    id: 1191,
    name: "dev",
    segments: []
  },
  {
    id: 1192,
    name: "credit",
    folder: "Embarazadas",
    segments: [{
        "name": "general",
      },
      {
        "name": "custom",
      }
    ]
  },
  {
    id: 1311,
    name: "box",
    segments: [{
      "name": "custom",
      "line_id": 1431,
      "id": 21,
      "active": true
    }]
  },
  {
    id: 2000,
    name: "sin folder",
    folder: null,
    segments: [{
        "name": "custom",
      },
      {
        "name": "general",
      }
    ],
  },
  {
    id: 2000,
    name: "credit card",
    segments: [{
      "name": "general",
    }],
  },
]

I need to get all objects with segment "general"

i tried with Ramda doing this but i did not get the result, first i did a maps of the lines, and then a filter. The problem is that sometimes segments attribute arrives empty

const filterLinesBySegments = (lines) => {
  const filter = (line) => {
    const hasSegments =R.filter(seg => seg["name"] === "general")(line.segments)
    const newLine = R.compose(
      R.assoc("segments", hasSegments),
    )(line)
    return newLine

  }
  const new= R.map(item => {
      return R.filter(line => {
        return filter(line)
      })(item)

  })(lines)

  return new;
}   

To keep only lines which has a general segment, you can use R.filter, with R.where to filter by a specific property. Since segments is an array, use R.any to search if some of the objects has the name of general .

To remove custom from segment you can evolve the object's segments, and reject all items with name: custom .

 const { filter, where, any, propEq, reject, evolve, pipe, map } = R const filterLinesBySegments = filter(where({ segments: any(propEq('name', 'general')) })) const filterCustomFromSegments = evolve({ segments: reject(propEq('name', 'custom')) }) const fn = pipe( filterLinesBySegments, map(filterCustomFromSegments), ) const lines = [{"id":1191,"name":"dev","segments":[]},{"id":1192,"name":"credit","folder":"Embarazadas","segments":[{"name":"general"},{"name":"custom"}]},{"id":1311,"name":"box","segments":[{"name":"custom","line_id":1431,"id":21,"active":true}]},{"id":2000,"name":"sin folder","folder":null,"segments":[{"name":"custom"},{"name":"general"}]},{"id":2000,"name":"credit card","segments":[{"name":"general"}]}] const result = fn(lines) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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