Skip to content

Commit

Permalink
feat: 新增 mergeObjectArray 方法
Browse files Browse the repository at this point in the history
  • Loading branch information
D-xuanmo committed Dec 1, 2024
1 parent 5ef21c5 commit b19de0f
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import { debounce } from '@xuanmo/utils'
|throwError|统一报错信息处理||
|debugWarn|警告信息统一处理||
|deleteArrayItems|指定删除数组的某些元素||
|mergeObjectArray|合并两个数组||
|pickLastItem|选择数组的最后一项元素||
|treeToMap|树形数据转 map||
|firstLetterLowercase|首字母小写||
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@xuanmo/utils",
"version": "0.0.3",
"version": "0.0.4",
"author": {
"name": "xuanmo",
"email": "[email protected]"
Expand Down
22 changes: 22 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,26 @@ export function pickLastItem<T extends unknown[] = []>(source: T): T[number] {
return source[source.length - 1]
}

/**
* 合并两个数组,只会合并一级对象
* @param target 目标数组
* @param source 源数组
* @param uniqueKey 唯一标识
*/
export function mergeObjectArray<T extends Record<string, any>>(target: T[], source: T[], uniqueKey: keyof T): T[] {
const map = new Map<string, T>()
source.forEach((item: T) => {
map.set(item[uniqueKey], item)
})
target.forEach((item: T) => {
const sourceItem = map.get(item[uniqueKey])
if (sourceItem) {
map.set(item[uniqueKey], { ...sourceItem, ...item })
} else {
map.set(item[uniqueKey], item)
}
})
return Array.from(map.values())
}

export { deleteArrayItems }
10 changes: 9 additions & 1 deletion test/array.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
const { deleteArrayItems } = require('../dist/index.cjs')
const { deleteArrayItems, mergeObjectArray } = require('../dist/index.cjs')

test('deleteArrayItems', () => {
expect(deleteArrayItems([1], [1, 2, 3])).toStrictEqual([2, 3])
expect(deleteArrayItems(['22'], ['22', '33'])).toStrictEqual(['33'])
expect(deleteArrayItems(['22'], [{ id: '22' }, { id: '33' }], 'id')).toStrictEqual([{ id: '33' }])
})

test('mergeObjectArray', () => {
const source = [{ id: 1 }, { id: 2 }, { id: 3 }]
const target = [{ id: 1, name: '1' }]
expect(mergeObjectArray(source, target, 'id')).toStrictEqual([{ id: 1, name: '1' }, { id: 2 }, { id: 3 }]
)
})

0 comments on commit b19de0f

Please sign in to comment.