JSON嵌套" nth level"对象数组转换为多维数组

时间:2015-12-09 08:06:30

标签: javascript arrays json

参考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]
]

2 个答案:

答案 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)

Array.prototype.forEach()

的帮助下
  

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