dav*_*ong 2 javascript arrays object ramda.js
我最近开始使用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 = {...}
}
]
Run Code Online (Sandbox Code Playgroud)
相同的ID代表同一个人。即,arrayOne中的id 1与arrayTwo中的id 1引用同一个人。因此,属性也相同。这三个数组之间的唯一区别是特殊属性。我需要合并每个特殊属性的整个对象,以便所有三个特殊属性都在具有相应ID的对象中。
像这样:
const newArray = [
{
id = 1,
attributes = {...},
specialProperty1 = {...},
specialProperty2 = {...},
specialProperty3 = {...}
},
{
id = 2,
attributes = {...},
specialProperty1 = {...},
specialProperty2 = {...},
specialProperty3 = {...}
},
]
Run Code Online (Sandbox Code Playgroud)
另外,这是在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)Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2561 次 |
| 最近记录: |