我最近开始使用 Ramda 来处理 JSONAPI 的响应,在处理复杂的关系时遇到了一些麻烦。我有一个包含三个较小数组的大数组,我需要合并三个较小的数组,但每个数组都有不同的财产。我需要一个具有这三种不同属性的数组。
例如:
const bigArray = [[...], [...], [...]]
arrayOne = [
{
id = 1,
attributes = {...},
specialProperty1 = {...}
},
{
id = 2,
attributes = {...},
specialProperty1 = {...}
}
]
arrayTwo = [
{
id = 1,
attributes = {...},
specialProperty2 = {...}
},
{
id = 2,
attributes = {...},
specialProperty2 = {...}
}
]
arrayThree = [
{
id = 1,
attributes = {...},
specialProperty3 = {...}
},
{
id = 2,
attributes = {...},
specialProperty3 = {...}
}
]
相同的 ID 代表同一个人。即 arrayOne 中的 id 1 与 arrayTwo 中的 id 1 引用同一个人。因此属性也相同。这三个数组之间的唯一区别是特殊属性。我需要合并每个特殊属性的整个对象,以便所有三个特殊属性都位于具有相应 id 的对象中。
像这样:
const newArray = [
{
id = 1,
attributes = {...},
specialProperty1 = {...},
specialProperty2 = {...},
specialProperty3 = {...}
},
{
id = 2,
attributes = {...},
specialProperty1 = {...},
specialProperty2 = {...},
specialProperty3 = {...}
},
]
另外,这是在 Promise.All 中返回的,因此请务必注意,三个较小的数组都在一个大数组中。我认为这是最让我困惑的地方,我很难弄清楚使用哪些 Ramda 方法来引用大数组中的三个数组。
解决此问题的一种方法是按每个数组的
id
属性进行索引,然后通过匹配的 id
及其内容合并每个相应的数组元素。然后最后提取外部索引对象的值。
const
arrayOne = [
{
id: 1,
attributes: {},
specialProperty1: {}
},
{
id: 2,
attributes: {},
specialProperty1: {}
}
],
arrayTwo = [
{
id: 1,
attributes: {},
specialProperty2: {}
},
{
id: 2,
attributes: {},
specialProperty2: {}
}
],
arrayThree = [
{
id: 1,
attributes: {},
specialProperty3: {}
},
{
id: 2,
attributes: {},
specialProperty3: {}
}
],
fn = R.pipe(
R.map(R.indexBy(R.prop('id'))),
R.reduce(R.mergeWith(R.merge), {}),
R.values
),
newArray = fn([arrayOne, arrayTwo, arrayThree])
console.log(newArray)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>