簡體   English   中英

打字稿中的lodash _.get函數

[英]lodash _.get function in typescript

我在谷歌搜索后得到的感覺很多lodash的功能可以通過原生打字稿來實現,但我找不到_.get函數的簡單答案...

在lodash中,使用_.get函數提醒1

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

有沒有辦法只用打字稿來達到同樣的效果?

在痛苦的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); 

/**
 * 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 '';
    }
};

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM