gpt4 book ai didi

javascript - 使用 Ramda 进行 map 和深度对象

转载 作者:行者123 更新时间:2023-12-02 21:19:42 24 4
gpt4 key购买 nike

我需要按“段”属性进行过滤,在本例中我需要按段进行过滤:[名称:“常规]

我有以下数组

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",
}],
},
]

我需要获取所有带有“general”段的对象

我尝试用 Ramda 这样做,但没有得到结果,首先我做了一个线路图,然后是一个过滤器。问题是有时段属性到达为空

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;
}

最佳答案

要仅保留具有常规段的行,您可以使用 R.filter 和 R.where 按特定属性进行过滤。由于segments是一个数组,因此使用R.any来搜索是否某些对象的namegeneral

要从分段中删除自定义,您可以演化对象的分段,并拒绝所有带有 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>

关于javascript - 使用 Ramda 进行 map 和深度对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60880496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com