如何从JavaScript中的数组键列表创建子关联对象?

我有一个来自用户输入的对象。该对象的键由逗号分隔,我只想将这些键分开并制成该对象的键。

The key_array below is dynamic from user input, generates a different array each time, below I give you an example. I have shown the object in my code which you can see below. you can also see the output by running that code.

var main_array = {};
var key_array = {
    'user,name' : 'user name',
    'user,email' : 'Email address',
    'order,id' : 123456,
    'order,qty' : 2,
    'order,total' : 300,
    'order,product,0,name' : "product1",
    'order,product,0,qty' : 1,
    'order,product,0,price' : 100,
    'order,product,1,name' : "product2",
    'order,product,1,qty' : 1,
    'order,product,1,price' : 200,
};

for (keys in key_array){
    var value = key_array[keys];

    // What do I do here to get the output I want?
    main_array['[' + keys.split(",").join('][')+ ']'] = value;
}
console.log(main_array);

运行上面的代码将为您提供以下错误的输出。还有我不想要的输出。

{
    [order][id]: 123456,
    [order][product][0][name]: "product1",
    [order][product][0][price]: 100,
    [order][product][0][qty]: 1,
    [order][product][1][name]: "product2",
    [order][product][1][price]: 200,
    [order][product][1][qty]: 1,
    [order][qty]: 2,
    [order][total]: 300,
    [user][email]: "Email address",
    [user][name]: "user name"
}

我想要以下类似JSON的输出,所以请告诉我该怎么做。

{
    "user":{
        "email" : "Email address",
        "name"  : "user name"
    },
    "order":{
        "id"    : 123456,
        "qty"   : 2,
        "total" : 300,
        "product":[
            {
                "name"  : "product1",
                "price" : 100,
                "qty"   : 1
            },{
                "name"  : "product2",
                "price" : 200,
                "qty"   : 1
            }
        ]
    }
}

Note: Please do not use eval, as using eval in this way is terribly unreliable, bad work and unsafe. Because I get all my data from user input, the likelihood of abuse can increase.