Kebab file names

This commit is contained in:
Angelos Chalaris
2023-04-27 21:58:35 +03:00
parent 1d189c709a
commit 61200d90c4
440 changed files with 0 additions and 0 deletions

29
snippets/deep-merge.md Normal file
View File

@ -0,0 +1,29 @@
---
title: Deep merge objects
tags: object,function
author: chalarangelo
cover: coffee-drip
firstSeen: 2021-07-25T05:00:00-04:00
---
Deeply merges two objects, using a function to handle keys present in both.
- Use `Object.keys()` to get the keys of both objects, create a `Set` from them and use the spread operator (`...`) to create an array of all the unique keys.
- Use `Array.prototype.reduce()` to add each unique key to the object, using `fn` to combine the values of the two given objects.
```js
const deepMerge = (a, b, fn) =>
[...new Set([...Object.keys(a), ...Object.keys(b)])].reduce(
(acc, key) => ({ ...acc, [key]: fn(key, a[key], b[key]) }),
{}
);
```
```js
deepMerge(
{ a: true, b: { c: [1, 2, 3] } },
{ a: false, b: { d: [1, 2, 3] } },
(key, a, b) => (key === 'a' ? a && b : Object.assign({}, a, b))
);
// { a: false, b: { c: [ 1, 2, 3 ], d: [ 1, 2, 3 ] } }
```