美文网首页
lodash中object.get方法的一个坑

lodash中object.get方法的一个坑

作者: foolchen | 来源:发表于2021-02-02 17:06 被阅读0次

问题

使用lodash中的get方法时,设置了defaultValue还是会获取到空值null

示例

const { get } = require('lodash/object');

const json = {
  key1: 'This is a string',
  key2: undefined,
  key4: null
};

const v1 = get(json, 'key1', '');
console.log('===>v1', `value = ${JSON.stringify(v1)}`, `type = ${typeof v1}`, `expect = ${json.key1}`);

const v2 = get(json, 'key2', '');
console.log('===>v2',`value = ${JSON.stringify(v2)}`, `type = ${typeof v2}`, `expect = ''`);

const v3 = get(json, 'key3', '');
console.log('===>v3', `value = ${JSON.stringify(v3)}`, `type = ${typeof v3}`, `expect = ''`);

const v4 = get(json, 'key4', '');
console.log('===>v4', `value = ${JSON.stringify(v4)}`, `type = ${typeof v4}`, `expect = ''`);

如上的代码中,v2v3v4的值,预期都是空字符串''。实际结果如下:

===>v1 value = "This is a string" type = string expect = This is a string
===>v2 value = "" type = string expect = ''
===>v3 value = "" type = string expect = ''
===>v4 value = null type = object expect = ''

处理方案

查看了get方法的源码:

/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function get(object, path, defaultValue) {
  var result = object == null ? undefined : baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

仅在获取到值为undefined的情况下才会使用defaultValue来替代(而且注释里也写了)。

提醒自己在使用第三方库时一定要仔细看说明。

相关文章

网友评论

      本文标题:lodash中object.get方法的一个坑

      本文链接:https://www.haomeiwen.com/subject/uppytltx.html