用ramda合并三个数组

Merge three arrays with ramda

我最近开始使用 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>