繁体   English   中英

用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM