如何缩进一个二维数组
How to indent a two dimensional array?
我试图创建一个JSON文件的array
命名为table
table
是一个二维数组,它的第二层包含:
[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>');
相关文章:
- 作为一个二维数组,从ajax接收
- 将一个二维数组传递给javascript中的函数
- Javascript:一个二维数组的字符串
- 将一个外部二维数组映射到另一个二维数组(javascript)
- Javascript使用map从一维数组创建一个二维数组
- 使用Java.lang.reflect.array.newInstance创建一个带有Java反射的二维数组
- 用Javascript创建一个给定宽度和高度的二维数组
- 用javascript从二维数组中选择一个二维数组
- 设置一个可变长度的二维数组
- 循环通过一个数组创建一个二维数组-循环不工作
- 移动一个二维数组
- 有没有一种方法可以将一个元素从二维数组内部移动到数组中的另一个位置,而不移动其他元素?
- 连接一个二维数组
- 将二维数组中的 ID 与另一个二维数组中的 ID 进行比较
- 如何缩进一个二维数组
- 从常规数组创建一个新的二维数组
- 如何从另一个二维数组中提取一个二维数组区域
- 在javascript中创建一个不同长度的自定义二维数组
- 将二维数组的元素复制到另一个二维数组中
- JavaScript:使用第一个“行”将二维数组转换为对象数组来定义属性