使用未知的字符串数组填充多维对象

时间:2014-09-10 18:08:06

标签: javascript recursion multidimensional-array

假设我有一个未知的字符串数组,例如:

arr = [fruit/bananas:10, fruit/apples/0:5, fruit/apples/1:8, fruit/apples/2:7, car/honda/civic:1];  

我希望填充一个对象,使每个数组值都是其对象值的路径(即arr成为下面的obj):

obj = {
      'fruits' :{
               'bananas' : 10,
               'apples'  : [5,8,7]
       },
       'car'   :{
               'honda':{
                       'civic': 1
                }
       }
}; 

我只是想知道什么类型的递归函数是最好的,因为每个值的实际数组长度是未知的,所以只需要拆分' /'和填充不会工作(我可以弄清楚)

1 个答案:

答案 0 :(得分:0)

试试这个:

var arr = ['fruit/bananas:10', 'fruit/apples/0:5', 'fruit/apples/1:8', 'fruit/apples/2:7', 'car/honda/civic:1'];

function createObject(array) {
    var out = {};
    array.forEach(function(value) {
        var current = out,
            last = current,
            data = value.split(':'),
            keys = data[0].split('/'),
            lastKey = keys.pop();

        keys.forEach(function(key) {
            if(!current[key]) {
                current[key] = {};
            }
            last = current;
            current = current[key];
        });
        if(lastKey === '0') {
            current = last[keys.pop()] = [];
        }
        current[lastKey] = +data[1];
    });
    return out;
}

console.log(createObject(arr));

以下是 jsfiddle-demo