Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combine arrays of object #25

Closed
syuilo opened this issue Aug 18, 2022 · 5 comments
Closed

Combine arrays of object #25

syuilo opened this issue Aug 18, 2022 · 5 comments

Comments

@syuilo
Copy link

syuilo commented Aug 18, 2022

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!

@mesqueeb
Copy link
Owner

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

@syuilo
Copy link
Author

syuilo commented Aug 24, 2022

@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.

@mesqueeb
Copy link
Owner

@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
Copy link
Owner

@syuilo did this solve your issue?

@mesqueeb
Copy link
Owner

@syuilo I think this solved the issue. there is a test added for this as well now, you can check it here
#35

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants