【问题标题】:lodash _.get function in typescript打字稿中的lodash _.get函数
【发布时间】:2016-10-20 08:49:22
【问题描述】:

经过一番谷歌搜索后,我感觉 lodash 的许多功能都可以使用本机打字稿来实现,但我找不到 _.get 函数的直接答案...

在lodash下面,使用_.get函数alerts 1

let obj = {a:{b:1}};
let a = _.get(obj, 'a.b');
alert(a);

有没有办法只用打字稿达到相同的结果?

【问题讨论】:

  • 我还没有找到任何现实生活中的场景,但是谁能告诉我为什么 .get() 函数甚至有用而不是 prop 表示法?如果路径未定义,是否只是为了能够返回默认值?
  • @felipe:恕我直言,当您需要预先访问深度未知的对象属性的动态“路径”时。

标签: javascript typescript lodash


【解决方案1】:

在纯 Javascript 中,您可以通过遍历给定的对象来分割路径并减少路径。

function getValue(object, path) {
    return path.
        replace(/\[/g, '.').
        replace(/\]/g, '').
        split('.').
        reduce((o, k) => (o || {})[k], object);
}

var obj = { a: { b: 1 } },
    a = getValue(obj, 'a.b');

console.log(a);

【讨论】:

  • 这正是我想要的,我测试了嵌套和对象数组,完美满足我的需求
【解决方案2】:
/**
 * Get value of a property from a nested object.
 * Example:
 * var x = { a: {b: "c"} };
 * var valueOf_b = getDeepValue(x, ["a", "b"]);
 *
 * @param  {object}     Object           The Object to get value from
 * @param  {KeyArray}   Array[String]    An array of nested properties. ex. ["property", "childProperty"]
 */
const getDeepValue = (object, keyArray) => {
    const extractValue = (obj, kArray) => {
        const objProperty = obj[kArray[0]];
        if (kArray.length >= 1) {
            const newKeyArray = kArray.splice(1, kArray.length);
            if (newKeyArray.length === 0) return objProperty;
            return extractValue(objProperty, newKeyArray);
        }
        return objProperty;
    };

    try {
        const value = extractValue(object, keyArray.slice());
        if (value === undefined || typeof value === 'object') {
            console.warn("Unable to retrieve value from object for key ", keyArray);
            return '';
        } else {
            return value;
        }
    } catch (e) {
        console.warn("Exception: Unable to retrieve value from object for key ", keyArray);
        return '';
    }
};

【讨论】:

    【解决方案3】:

    使用 ES6 默认参数可能会更简洁:

    const get = (o, path) => path.split('.').reduce((o = {}, key) => o[key], o);
    console.log(get({ a: { b: 43 } }, 'a.b')); // 43
    

    即使遇到 undefined,上面的内容也会一直挖掘到底部。 另一种方法是递归,您必须在调用它之前拆分:

    function get(object, [head, ...tail]) {
        object = object[head];
        return tail.length && object ? get(object, tail) : object;
    }
    
    console.log(get({ a: { b: 43 } }, 'a.b'.split('.'))); // 43
    

    【讨论】:

    • 这似乎无法处理数组。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多