通过键|从嵌套对象获取值重构' for循环'

时间:2017-09-15 11:00:23

标签: javascript object refactoring

我有下面的方法,我从嵌套对象获取值,想要以最佳方式重构它,但由于linting规则不能使用Object.hasOwnProperty

export const getValueFromNestedObject = (obj = {}, key = '') => {
    let result;
    for (let i = 0; i< Object.keys(obj).length; i++) {
        if (typeof obj[Object.keys(obj)[i]] === 'object') {
            result = getValueFromNestedObject(obj[Object.keys(obj)[i]], key);
            if(typeof result != 'undefined') {
                return result;
            }
        } else if (Object.keys(obj)[i] === key) {
            return obj[key];
        }
    }
}


const valueObj = {
    '@close' : {
        'type': 'button',
        'dom' : {
            'data-linkName' : 'Close'
        }
    },
    '@popupText': {
        'type': 'HTML',
        'options': {
            'html': 'Pop Up Text that is required as result'
            'label': 'Heads Up'
        }
    }
};

const key = 'html';
console.log(getValueFromNestedObject(valueObj, key));
expect(getValueFromNestedObject(valueObj, key)).toEqual('Pop Up Text that is required as result')

0 个答案:

没有答案