参考JSON array conversion into multi dimension array。我想将nested object
转换为多维数组。
[{
"name": "level1",
"subCategory": [{
"name": "level2",
"subCategory": [{
"name": "level3",
"val": 1,
"subCategory": null
}]
}]
}, {
"name": "level1",
"subCategory": [{
"name": "level2",
"subCategory": [{
"name": "level3",
"val": 2,
"subCategory": null
}]
}]
}, {
"text": "level1",
"subCategory": [{
"name": "level2",
"subCategory": [{
"name": "level3",
"val": 3,
"subCategory": null
}]
}]
}]
进入
[
["level1", "level2", "level3", 1]["level1", "level2", "level3", 2],
["level1", "level2", "level3", 3]
]
答案 0 :(得分:0)
检查此fiddle
var sampleData = [{
"name": "level1",
"subCategory": [{
"name": "level2",
"subCategory": [{
"name": "level3",
"val": 1,
"subCategory": null
}]
}]
}, {
"name": "level1",
"subCategory": [{
"name": "level2",
"subCategory": [{
"name": "level3",
"val": 2,
"subCategory": null
}]
}]
}, {
"text": "level1",
"subCategory": [{
"name": "level2",
"subCategory": [{
"name": "level3",
"val": 3,
"subCategory": null
}]
}]
}];
function transform( data )
{
var output = [];
for ( var counter = 0; counter < data.length; counter++ )
{
var obj = data[ counter ];
var level1 = obj.text;
var level2 = obj.subCategory[ 0 ];
var level3 = obj.subCategory[ 0 ].subCategory[ 0 ];
output.push( [ obj.text, level2.name, level3.name, level3.val ] );
}
return output;
}
console.log( transform( sampleData ) );
答案 1 :(得分:0)
forEach()
方法每个数组元素执行一次提供的函数。
var data = [{ "name": "level1", "subCategory": [{ "name": "level2", "subCategory": [{ "name": "level3", "val": 1, "subCategory": null }] }] }, { "name": "level1", "subCategory": [{ "name": "level2", "subCategory": [{ "name": "level3", "val": 2, "subCategory": null }] }] }, { "text": "level1", "subCategory": [{ "name": "level2", "subCategory": [{ "name": "level3", "val": 3, "subCategory": null }] }] }],
result = [];
function iterator(array, names) {
names = names || [];
array.forEach(function (a) {
var n = names.concat(a.name);
if (Array.isArray(a.subCategory)) {
iterator(a.subCategory, n);
} else {
result.push(n.concat(a.val));
}
});
}
iterator(data);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');