const assignIfValueTruthy = (o, [k, v]) => (v ? { ...o, [k]: v } : o);
时间: 2024-03-05 08:50:43 浏览: 23
The `assignIfValueTruthy` function takes in an object `o` and a tuple `[k, v]`. It returns a new object that is a copy of `o` with a new key-value pair `[k, v]` added, but only if the value `v` is truthy.
Here's how the function works:
- If `v` is falsy (e.g. `undefined`, `null`, `false`, `0`, `NaN`, or an empty string), the function returns the original object `o` unchanged.
- If `v` is truthy, the function returns a new object that is a copy of `o`, but with the new key-value pair `[k, v]` added.
The function uses object spread syntax (`{...o}`) to create a shallow copy of the original object `o`, and then adds the new key-value pair using computed property names (`[k]: v`). The `?` operator is used to check if `v` is truthy.
Here's an example usage of the function:
```
const obj = { foo: 'bar' };
const pair1 = ['baz', 123];
const pair2 = ['qux', null];
const newObj = assignIfValueTruthy(obj, pair1); // { foo: 'bar', baz: 123 }
const newObj2 = assignIfValueTruthy(newObj, pair2); // { foo: 'bar', baz: 123 }
```
In this example, `assignIfValueTruthy` is called twice to add two key-value pairs to the original object `obj`. The first pair `[baz, 123]` is truthy, so it is added to the object and a new object is returned. The second pair `[qux, null]` is falsy, so the original object is returned unchanged.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)