如何从平面数组创建JavaScript多维数组?

时间:2014-08-07 19:13:02

标签: javascript arrays multidimensional-array

我有一个示例,其中包含一些我想要更改的值,此处为链接http://jsfiddle.net/k83hj1jb/

结果是一个平面阵列:

[
    {"name":"options[11][140]","value":"140"},
    {"name":"options[8][99]","value":"99"},
    {"name":"options[8][103]","value":"103"}
]

我希望改变这样的事情:

[
    {
        "options":
        {
            "11":{"140":"140"},
            "8":
            {
                "99":"99",
                "103":"103"
            }
        }
    }
]

有简单的方法吗?

2 个答案:

答案 0 :(得分:1)

让我们调用您当前拥有的数组flatArr和您想要的数组nestArr

以下是nestArrflatArr的计算方法:

var getNestArr = function (flatArr) {
    var nestObj = {'options': {}}, obj, opts, parts;
    for (i = 0; i < flatArr.length; i += 1) {
        obj = flatArr[i];
        opts = obj.name;
        parts = opts.replace('options[', '').slice(0, -1).split('][');
        if (!nestObj.options.hasOwnProperty(parts[0])) {
            nestObj.options[parts[0]] = {};
        }
        nestObj.options[parts[0]][parts[1]] = obj.value;
    }
    return [nestObj]; // returns an array instead of object.
};

测试:

var flatArr = [
    {"name":"options[11][140]","value":"140"},
    {"name":"options[8][99]","value":"99"},
    {"name":"options[8][103]","value":"103"}
];
var nestArr = getNestArr(flatArr);
console.log(JSON.stringify(nestArr));

输出结果为:

[{"options":{"8":{"99":"99","103":"103"},"11":{"140":"140"}}}] 

结果正是您想要的。但是,您可能希望将nestObj返回[nestObj]

希望这有帮助。

答案 1 :(得分:-1)

是的,您可以使用php而不是javascript:

// this is the start json
$json = '[{"name":"options[11][140]","value":"140"},
          {"name":"options[8][99]","value":"99"},
          {"name":"options[8][103]","value":"103"}]';

// decode the json to a php array
$array = json_decode($json, true);

// foreach value of the array
foreach ($array as $value) {

    // initialize a new array
    $option_value = array();

    // access to name value
    $option = $value["name"];

    // explode the string to an array where separator is the square bracket
    $option_values = explode("[", $option);

    // retrieve the two values between the options brackets removing the last square bracket
    $option_value[] = rtrim($option_values[1], "]");
    $option_value[] = rtrim($option_values[2], "]");

    // add a new array element in position of the first value of the option brackets: the array is composed by the second value and the value within the key "value"
    $new_array["options"][$option_value[0]][] = array($option_value[1], $value["value"]);

}

// at the end, encode it to the original json data
$json = json_encode($new_array);

// let show us the result on the screen
var_dump($json);

如果有任何疑问,或者如果我看起来你不那么清楚,请告诉我,我将编辑我的答案