有没有 Ramda 方法来合并这两个数据数组?

问题描述 投票:0回答:1

我需要合并两个相同形状的数据数组。

我的工作代码是这样的:

import * as R from 'ramda'

const expected = [
    [
        {
            "zeroData": false,
            "responseCount": [
                0,
                0,
                1,
                9
            ],
            "responsePercent": [
                0,
                0,
                0.1,
                0.9
            ],
            "index": 9.666666666666666,
            "stdDev": 0.9999999999999999,
            "expectedStdDev": 1.651740425387243
        }
    ]
]

const t1 = [
    [
        {
            "zeroData": false,
            "responseCount": [
                0,
                0,
                1,
                9
            ],
            "responsePercent": [
                0,
                0,
                0.1,
                0.9
            ],
            "index": 9.666666666666666,
            "stdDev": 0.9999999999999999
        }
    ]
]

const t2 = [
    [
        {
            "expectedStdDev": 1.651740425387243
        }
    ]
]

test('merge', () => {
    const merged = t1.map((arr1, idx1) => {
        return arr1.map((obj, idx2) => ({...obj, ...t2[idx1][idx2]}))
    })

    expect(merged).toStrictEqual(expected)
})

有没有一种简单而优雅的 Ramda 方法来做到这一点?尤其是一个通用的解决方案,允许指定合并应该发生的深度。

尝试了 R 函数的各种组合,但没有成功

javascript functional-programming ramda.js
1个回答
0
投票

根据lib的官方文档,可以使用

mergeAll
。 您首先需要使用
concat
展平数组,然后可以使用
mergeAll

这就是实现它的方法:

import * as R from 'ramda'

const expected = [
    [
        {
            "zeroData": false,
            "responseCount": [
                0,
                0,
                1,
                9
            ],
            "responsePercent": [
                0,
                0,
                0.1,
                0.9
            ],
            "index": 9.666666666666666,
            "stdDev": 0.9999999999999999,
            "expectedStdDev": 1.651740425387243
        }
    ]
]

const t1 = [
    [
        {
            "zeroData": false,
            "responseCount": [
                0,
                0,
                1,
                9
            ],
            "responsePercent": [
                0,
                0,
                0.1,
                0.9
            ],
            "index": 9.666666666666666,
            "stdDev": 0.9999999999999999
        }
    ]
]

const t2 = [
    [
        {
            "expectedStdDev": 1.651740425387243
        }
    ]
]

test('merge', () => {
    const merged = R.mergeAll([].concat(...t1, ...t2));

    expect(merged).toStrictEqual(expected)
})

您可以阅读本文以了解更多信息:https://ramdajs.com/docs/#mergeAll

© www.soinside.com 2019 - 2024. All rights reserved.