我想将其内置到我的compose
函数中,以使record
的值到达对象的顶层,而其余键保持原样:
{
record: {
seasons: [
1
],
colors: [
2
]
},
tag_ids: [
2091
]
}
我追求的结果:
{
seasons: [
1
],
colors: [
2
],
tag_ids: [
2091
]
}
任何键可能或可能不存在。
我一直用compose
函数中的ramda方式来挠头。目前,我正在查看toPairs
,并做了一些相当长的变换,没有运气。
您可以将R.chain与R.merge和R.prop结合使用,通过将其与原始对象合并来拼合密钥的内容,然后可以省略原始密钥。
const { pipe, chain, merge, prop, omit } = R
const fn = key => pipe(
chain(merge, prop(key)), // flatten the key's content
omit([key]) // remove the key
)
const data = { record: { seasons: [1], colors: [2] }, tag_ids: [2091] }
const result = fn('record')(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
您可以使用点差运算符。
const startingWithAllProps = {
record: {
seasons: [
1
],
colors: [
2
]
},
tag_ids: [
2091
]
}
const startingWithoutRecord = {
tag_ids: [
2091
]
}
const startingWithoutTagIds = {
record: {
seasons: [
1
],
colors: [
2
]
}
}
const moveRecordUpOneLevel = (startingObject) => {
const temp = {
...startingObject.record,
tag_ids: startingObject.tag_ids
}
return JSON.parse(JSON.stringify(temp)) // To remove any undefined props
}
const afterTransformWithAllProps = moveRecordUpOneLevel(startingWithAllProps)
const afterTransformWithoutRecord = moveRecordUpOneLevel(startingWithoutRecord)
const afterTransformWithoutTagIds = moveRecordUpOneLevel(startingWithoutTagIds)
console.log('afterTransformWithAllProps', afterTransformWithAllProps)
console.log('afterTransformWithoutRecord', afterTransformWithoutRecord)
console.log('afterTransformWithoutTagIds', afterTransformWithoutTagIds)
在纯JS而不是Ramda中,这可能更简单:
const data = { record: { seasons: [1], colors: [2] }, tag_ids: [2091] }
const flattenRecord = ({record = {}, ...rest}) => ({...record, ...rest})
flattenRecord(data) //=> {"colors": [2], "seasons": [1], "tag_ids": [2091]}
如果您仍然想使用Ramda作为解决方案,请考虑研究R.mergeLeft
(或R.mergeLeft
)和R.mergeRight
。
这可能也有帮助!
R.omit
R.omit