merge-anything icon indicating copy to clipboard operation
merge-anything copied to clipboard

Combine arrays of object

Open syuilo opened this issue 1 year ago • 3 comments

Thanks for creating this library, there are several libraries that do deep merge, but this is the only one I've seen written in TypeScript.

I would like to see a default function for deep merging arrays of objects, such as the one introduced in the deepmerge library. This means that I want to use the following strategy for merging:

const x = { a: [{ foo: 42 }] }
const y = { a: [{ bar: 42 }] }

const expect = { a: [{ foo: 42, bar: 42 }] }

Or please provide a sample that uses mergeAndCompare to achieve the same process.

Thanks!

syuilo avatar Aug 18 '22 08:08 syuilo

@syuilo did you see this section of the readme? https://github.com/mesqueeb/merge-anything#concat-arrays

mesqueeb avatar Aug 24 '22 05:08 mesqueeb

@syuilo did you see this section of the readme? https://github.com/mesqueeb/merge-anything#concat-arrays

Yes. But I do not want to concat.

syuilo avatar Aug 24 '22 06:08 syuilo

@syuilo I see!!

something like this? can you test it out?

import { isArray } from 'is-what'
import { merge } from 'merge-anything'

export function concatArrays (originVal: any, newVal: any): any | any[] {
  if (isArray(originVal) && isArray(newVal)) {
    // concat & merge logic
    const overlappingPart = originVal.slice(0, newVal.length)

    return overlappingPart
      .map((p, i) => newVal[i] ? merge(p, newVal[i]) : p)
      .concat(newVal.length > originVal.length ? originVal.slice(newVal.length) : newVal.slice(originVal.length))
  }
  return newVal // always return newVal as fallback!!
}

if this is ok, greatly appreciate a PR with this fn exported similarly to mergeAndConcat, added to the README and some automated tests added < 3

mesqueeb avatar Aug 25 '22 04:08 mesqueeb