如何缩进二维数组?

时间:2015-08-14 15:08:25

标签: javascript arrays json

我尝试使用名为array的{​​{1}}创建JSON文件 table是一个二维数组,第二级包含:

  

[name,id,parent]

我希望将它们转换为JSON,但我不知道我是否朝着正确的方向前进,或者是否有更好的方法。你能救我吗?

提前致谢。

我的代码:



table




1 个答案:

答案 0 :(得分:2)

也许这符合您的需求。

对于JSON字符串,只需使用JSON.stringify(obj)

此解决方案主要采用channels方法。

function getChildren(parent) {
    // Array.reduce is a method which returns a value. the callback can have up to
    // 4 parameters, a start value `r`, if defined, otherwise the first element of the
    // array, the array element (maybe it starts with the second) `a`, the index (not
    // defined here) and the object itself (not defined here).
    // to make a structure i need to iterate over the given data `table` and look
    // for a given parent. if found then i have to look for their children and iterate
    // over the `table` again, until no children is found.
    return table.reduce(function (r, a) {
        // test if the parent is found
        if (a[2] === parent) {
            // if so, generate a new object with the elements of `cols` as properties
            // and the values of the actual array `a`
            // like { name: "name3", id: 3, parent: 0 }
            var row = cols.reduce(function (rr, b, i) {
                rr[b] = a[i];
                return rr;
            }, {});
            // create a new property `children`and assign children with the actual id
            // as parentId
            row['children'] = getChildren(a[1]);
            // push row to the result
            r.push(row);
        }
        // return the result
        return r;
    // start value for r is an empty array
    }, []);
}

var table = [
        ["name1", 1, 2],
        ["name2", 2, 3],
        ["name3", 3, 0],
        ["name4", 4, 1],
        ["name5", 5, 3]
    ],
    cols = ['name', 'id', 'parent'],
    obj = getChildren(0);

document.write('<pre>' + JSON.stringify(obj, null, 4) + '</pre>');