如何缩进一个二维数组

How to indent a two dimensional array?

本文关键字:二维数组 一个 缩进 何缩进      更新时间:2023-09-26

我试图创建一个JSON文件的array命名为tabletable是一个二维数组,它的第二层包含:

[name, id, parent]

,我想把它们转换成JSON,但我不知道我的方向是否正确,或者是否有更好的方法。你能帮我吗?

提前感谢。

我的代码:

var table = [
  ["name1", 1, 2],
  ["name2", 2, 3],
  ["name3", 3, 0],
  ["name4", 4, 1],
  ["name5", 5, 3]
];
function deepcheck(dad) {
  for (var i = 0; i < table.length; i++) {
    if (table[i][2] === dad) {
      console.log('{' + table[i][1] + '}');
      var h = table[i][1];
      deepcheck(h);
    }
  }
}
for (var i = 0; i < table.length; i++) {
  if (table[i][2] === 0) {
    console.log('[{');
    console.log(table[i][0] + ',' + table[i][1] + '[');
    var t = table[i][1];
    deepcheck(t);
  }
}

也许这符合你的需要。

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

这个解决方案大量使用了Array.prototype.reduce()方法。

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>');