RamdaJS 转换对象并使用另一个列表进行查找 [英] RamdaJS transform object and do lookup with another lists
本文介绍了RamdaJS 转换对象并使用另一个列表进行查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
let children = [
{ "name": "Bob", "age": 8, "father": "Mike" },
{ "name": "David", "age": 10, "father": "Mike" },
{ "name": "Amy", "age": 2, "father": "Mike" },
{ "name": "Jeff", "age": 11, "father": "Jack" }
]
let schoolList = [
{ "name": "Bob", "class": "8-A", "school": "School 1" },
{ "name": "David", "class": "10-B", "school": "School 1" },
{ "name": "Amy", "class": "2-A", "school": "School 1" },
{ "name": "Jeff", "class": "11-C", "school": "School 1" }
]
到目前为止我做了什么.
What have i done so far.
R.pipe(
R.groupBy(R.prop('father')),
R.map(R.applySpec({
father: R.pipe(R.head, R.prop('father')),
count: R.length,
kids: R.map(R.dissoc('father')),
class: R.map(R.prop('class'))R.find(R.propEq('name',R.pipe(R.head, R.prop('name'))), schoolList)
})),
R.values()
)(children)
预期输出是 class 属性附加到嵌套的 kids 数组中.
Expected output is class property is appended to nested kids array.
{
"father": "Jack",
"count" : 1,
"kids": [
{ "name": "Jeff", "age": 11, "class" : "11-C" }
]
}
推荐答案
如果实际的 schoolList
很长,我会使用 OriDrori 的答案.但如果它相当短,那么这可能会更简洁一些,即使效率较低:
If the actual schoolList
is quite long, I would use the answer from OriDrori. But if it's fairly short, then this might be a bit cleaner, even if less efficient:
const expandChild = schoolList => child => ({
...child,
class: defaultTo(
{class: 'unknown'},
find(propEq('name', child.name), schoolList)
).class
})
const groupChildren = schoolList => pipe(
groupBy(prop('father')),
map(applySpec({
father: pipe(head, prop('father')),
count: length,
kids: map(pipe(dissoc('father'), expandChild(schoolList)))
})),
values,
)
let children = [{ name: "Bob", age: 8, father: "Mike" }, { name: "David", age: 10, father: "Mike" }, { name: "Amy", age: 2, father: "Mike" }, { name: "Jeff", age: 11, father: "Jack" }, { name: "Sue", age: 9, father: "Jack" }]
let schoolList = [{ name: "Bob", class: "8-A", school: "School 1" }, { name: "David", class: "10-B", school: "School 1" }, { name: "Amy", class: "2-A", school: "School 1" }, { name: "Jeff", class: "11-C", school: "School 1" }]
console.log (groupChildren (schoolList) (children))
<script src="https://bundle.run/ramda@0.26.1"></script><script>
const {defaultTo, find, propEq, pipe, groupBy, map, applySpec, head, prop, length, dissoc, values} = ramda
</script>
注意 school
的默认值,以防孩子的名字不在 schoolList
中.
Note the default value given for school
in case the child's name is not in schoolList
.
这篇关于RamdaJS 转换对象并使用另一个列表进行查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文