tltr:看看javascript代码片段。
我有很多东西。
我想映射项目并更改它们的结构。
我需要保留一些属性,还需要设置一个新属性。但是,新属性值将基于我当前映射的项。
// change title to whatever shape you desire
const customTitleTransformation = title => title
const arrayOfItems = [
{
id: 'some id 1',
isSelected: true,
title: 'some title 1',
text: 'some text',
description: 'some description'
},
{
id: 'some id 2',
isSelected: false,
title: 'some title 2',
text: 'some text',
description: 'some description'
},
]
// I need array of items like:
// {
// id,
// isSelected,
// cells: [
// customTitleTransformation(title),
// text
// ]
// }
// REGULAR JAVASCRIPT WAY
const normalizedItems = arrayOfItems.map(item => ({
id: item.id,
isSelected: item.isSelected,
cells: [
customTitleTransformation(item.title),
item.text,
]
}))
console.log('first result ', normalizedItems)
// USING RAMDA
const normalizedItemsRamda = R.map(
R.compose(
R.pick(['id', 'isSelected', 'cells']),
R.set(R.lensProp('cells'), ['how do I set the array?'])
)
)(arrayOfItems)
console.log('ramda result ', normalizedItemsRamda)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
最佳答案
我认为这可能是一个applySpec
的例子。mapObject
函数定义新对象的形状。然后将该转换应用于arrayOfItems
。
当然,这是否更具可读性完全取决于您的欣赏:
// change title to whatever shape you desire
const customTitleTransformation = title => title
const arrayOfItems = [{
id: 'some id 1',
isSelected: true,
title: 'some title 1',
text: 'some text',
description: 'some description'
},
{
id: 'some id 2',
isSelected: false,
title: 'some title 2',
text: 'some text',
description: 'some description'
},
]
const mapObject = R.applySpec({
id: R.prop('id'),
isSelected: R.prop('isSelected'),
cells: R.juxt([
R.o(customTitleTransformation, R.prop('title')),
R.prop('text')
])
});
const normalizedItemsRamda = R.map(mapObject, arrayOfItems)
console.log('ramda result ', normalizedItemsRamda)
console.log('\n\nOriginal Items Unchanged:')
console.log(arrayOfItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>