为了账号安全,请及时绑定邮箱和手机立即绑定

js数据封装问题

js数据封装问题

月关宝盒 2018-12-21 19:14:00
{"config_name_0":"11","mountEnv_0_5723":{"lable":"22","val":"33","type":"1"},"mountEnv_1_5723":{"lable":"44","val":"55","type":"1"},"config_name_1":"66","mountEnv_0_4268":{"lable":"77","val":"88","type":"1"},"mountEnv_1_4268":{"lable":"99","val":"00","type":"1"}}这段数据转换成[{config_name:'11',mountEnv:[    {"lable":"22","val":"33","type":"1"},    {"lable":"44","val":"55","type":"1"}        ]},config_name:'66',mountEnv:[    {"lable":"77","val":"88","type":"1"},    {"lable":"99","val":"00","type":"1"}        ]    }]
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

var input = {"config_name_0":"11","mountEnv_0_5723":{"lable":"22","val":"33","type":"1"},"mountEnv_1_5723":{"lable":"44","val":"55","type":"1"},"config_name_1":"66","mountEnv_0_4268":{"lable":"77","val":"88","type":"1"},"mountEnv_1_4268":{"lable":"99","val":"00","type":"1"}};

var result = [];

var regName = /_(\d+)/;

var regMount = /_(\d+)_/;

for (var key in input) {

    if (typeof input[key] == 'string') {

        var index = key.match(regName)[1];

        if (!result[index]) result[index] = {config_name:'', mountEnv:[]};

        result[index]["config_name"] = input[key];

    } else {

        var index = key.match(regMount)[1];

        if (!result[index]) result[index] = {config_name:'', mountEnv:[]};

        result[index]["mountEnv"].push(input[key]);

    }

}

这个是根据config_name_x 和 mountEnv_x_ssss中的x来确定同一个对象的数据,但是按照lz的转化完数据来看,我没看出来确切的数据对应。。

我的转化结果


[{

config_name:'11',

mountEnv:[

    {"lable":"22","val":"33","type":"1"},

    {"lable":"77","val":"88","type":"1"}

        ]

},

config_name:'66',

mountEnv:[

    {"lable":"44","val":"55","type":"1"},

    {"lable":"99","val":"00","type":"1"}

        ]

    }

]

lz的是按照ssss的合并,但是前后顺序呢?

如果是可以保证前后顺序,那么可以这样


var input = {"config_name_0":"11","mountEnv_0_5723":{"lable":"22","val":"33","type":"1"},"mountEnv_1_5723":{"lable":"44","val":"55","type":"1"},"config_name_1":"66","mountEnv_0_4268":{"lable":"77","val":"88","type":"1"},"mountEnv_1_4268":{"lable":"99","val":"00","type":"1"}};

var result = [];

var regName = /_(\d+)/;

var index;

for (var key in input) {

    if (typeof input[key] == 'string') {

        index = key.match(regName)[1];

        if (!result[index]) result[index] = {config_name:'', mountEnv:[]};

        result[index]["config_name"] = input[key];

    } else {

        result[index]["mountEnv"].push(input[key]);

    }

}


查看完整回答
反对 回复 2019-01-14
  • 1 回答
  • 0 关注
  • 565 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信