如何将此嵌套对象转换为平面对象? [英] how to convert this nested object into a flat object?

查看:63
本文介绍了如何将此嵌套对象转换为平面对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我不知道如何用短语来表达问题.如果可能,请帮助进行编辑.

Sorry I don't know how to phrase the question title. Please help edit if possible.

我有一个这样的对象:

{
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
}

我想使它看起来像:

{
    'a': 'jack',
    'b.c': 'sparrow',
    'b.d.e': 'hahaha'
}

// so that I can use it this way:
a['b.d.e']

jQuery也可以.我知道对于嵌套对象,我可以使用a.b.d.e来获取hahaha,但是今天我必须像a['b.d.e']一样使用它-_-! 我怎样才能做到这一点?在此先感谢:)

jQuery is ok too. I know for the nested object, I can use a.b.d.e to get hahaha, but today I have to use it like a['b.d.e'] -_-!!! How can I achieve this? Thanks in advance :)

推荐答案

您可以使用递归函数对对象进行爬网并将其展平.

You could use a recursive function to crawl the object and flatten it for you.

var test = {
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
            e: 'hahaha'
        }
    }
};

function dive(currentKey, into, target) {
    for (var i in into) {
        if (into.hasOwnProperty(i)) {
            var newKey = i;
            var newVal = into[i];
            
            if (currentKey.length > 0) {
                newKey = currentKey + '.' + i;
            }
            
            if (typeof newVal === "object") {
                dive(newKey, newVal, target);
            } else {
                target[newKey] = newVal;
            }
        }
    }
}

function flatten(arr) {
    var newObj = {};
    dive("", arr, newObj);
    return newObj;
}

var flattened = JSON.stringify(flatten(test));
console.log(flattened);

这篇关于如何将此嵌套对象转换为平面对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆