defaultDeep的版本和覆盖undefined和null值的默认值

时间:2018-06-05 05:42:29

标签: javascript lodash

我正在寻找Lodash的defaultsdefaultsDeep版本,除了null之外,还会覆盖undefined个值。我查看了defaultsDeep的来源,但无法找到一种简单的方法来实现它。我宁愿使用一个简单的解决方案,可能是基于Lodash,而不是自己动手。

2 个答案:

答案 0 :(得分:2)

您可以使用lodash#mergeWith合并具有lodash#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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)