使用Ramda合并三个数组

4

最近我开始使用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 中返回的。因此,需要注意的是,这三个较小的数组都在一个大数组中。我认为这是最让我困扰的问题,我很难确定要使用哪些 Ramda 方法来引用大数组中的三个数组。


  1. 将大数组展平
  2. 按ID分组
  3. 连接
- Jonas Wilms
2
  1. .... 5) 利润
- Fallenreaper
1个回答

10
一种处理方法是通过每个数组的 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接