Reputation: 3
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;
}
Upvotes: 0
Views: 576
Reputation: 193087
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>
Upvotes: 1