JS数组串补丁名称数组(对象) [英] JS array string patch name to array(object)

查看:109
本文介绍了JS数组串补丁名称数组(对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JS数组的麻烦。
我有补丁名称(字符串)的样子(user.joey.friends.0.franc),我需要COM preSS看起来是这样的:

i have trouble with js array. I have patch name(string) look like ( "user.joey.friends.0.franc" ) and i need to "compress" to look like this:

console.log( parseArray( "user.joey.friends.0.franc" ) );
//Object {
            user: {
                joey: {
                    friends: {
                        0: {
                            franc: 1
                        }
                    }
                }
            }
        }

任何想法,该怎么办?

Any ideas, how to do that ?

推荐答案

下面是一个非递归的方式来获得你最那里的方式。

Here's a non recursive way to get you most of the way there.

function compress(str) {
    var split = str.split('.'), obj = {}, current = obj, i;

    for (i = 0; i < split.length; i++){
        current[split[i]] =  {} ;
        current = current[split[i]];
    }

    return obj;
}

这篇关于JS数组串补丁名称数组(对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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