javascript - 覆盖未定义和空值的 defaultDeep 和默认值的版本
问题描述
我正在寻找 Lodash 的版本,defaults
并且除了. 我已经查看了源代码,但无法找到一种简单的方法来让它工作。我宁愿使用一个可能基于 Lodash 的简单解决方案,也不愿使用我自己的解决方案。defaultsDeep
null
undefined
defaultsDeep
解决方案
您可以通过使用lodash#mergeWith
to merge objects withlodash#isNil
作为识别条件来确定变量是null
还是来解决此问题undefined
。
// Note: if you change `_.isNil` to `_.isUndefined`
// then you'd get the `_.defaults()` normal behavior
const nilMerge = (a, b) => _.isNil(a)? b: a;
const nilMergeDeep = (a, b) => (_.isObject(a) && !_.isArray(a))
// recursively merge objects with nilMergeDeep customizer
? _.mergeWith({}, a, b, nilMergeDeep)
// let's use our default customizer
: nilMerge(a, b);
// defaults not deep with null/undefined
const result1 = _.mergeWith({}, o1, o2, o3, nilMerge);
// defaults deep with null/undefined
const result2 = _.mergeWith({}, o1, o2, o3, nilMergeDeep);
const o1 = {
a: 1,
b: 2,
c: 3,
d: null,
x: {
x1: 1,
x2: 2,
x3: null
},
z: null
};
const o2 = {
a: 9999,
d: 4,
e: null,
f: 123,
x: {
x3: 3,
x4: null
},
z: ['a', 'b']
};
const o3 = {
b: 9999,
e: 5,
f: 2,
g: 234,
x: {
x4: 4,
x5: 5,
x6: ['hi', 'there']
},
z: ['c']
};
// Note: if you change `_.isNil` to `_.isUndefined`
// then you'd get the `_.defaults()` normal behavior
const nilMerge = (a, b) => _.isNil(a)? b: a;
const nilMergeDeep = (a, b) => (_.isObject(a) && !_.isArray(a))
// recursively merge objects with nilMergeDeep customizer
? _.mergeWith({}, a, b, nilMergeDeep)
// let's use our default customizer
: nilMerge(a, b);
// defaults not deep with null/undefined
const result1 = _.mergeWith({}, o1, o2, o3, nilMerge);
// defaults deep with null/undefined
const result2 = _.mergeWith({}, o1, o2, o3, nilMergeDeep);
console.log('defaults not deep with null/undefined');
console.log(result1);
console.log('defaults deep with null/undefined');
console.log(result2);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
推荐阅读
- bash - 如何使用 sed 或 awk 在文件的特定行插入特定字符?
- python - 如何在 scikit-learn 中使用交叉验证获得预测概率
- c - 如何正确构建具有字符结构的链表
- css - 带进度条的引导输入组
- angular - (激活)事件
当我运行 ng build --prod 时不起作用 - git - 有没有办法限制 ssh 密钥/用户访问 repo 的某些部分?
- php - 任何人都有使用 GCP 使用 PHP 和 Drive API 在 Google Drive 中创建文件夹的经验吗?
- c# - 为什么我的 DISTINCT 查询在 CosmosDB 数据资源管理器中停止工作,但在 C# API 中工作?
- java - 如何修复/学习有助于理解基本方法和类、Java 代码和单词问题
- sophoslabs-intelix - Intellix API 的限制