js
带有DEMO的纯解决方案,应该适用于任何深度的任何非递归对象/JSON 对象:
var jsonObj = [{"Id":1,"Category":"Category1","Comments":[{"Id":1,"Comment":"test"},{"Id":2,"Comment":"test 2"}]},{"Id":2,"Category":"Category2","Comments":[{"Id":1,"Comment":"test"}]},{"Id":3,"Category":"Category3","Comments":[{"Id":1,"Comment":"something"}, {"Id":2,"Comment":"test 2"}, {"Id":3,"Comment":"test 3"}, {"Id":4,"Comment":"something 4"}, {"Id":5,"Comment":"something 5"} ]}];
var obj2String = function (obj, indent) { // recursive method to print out all key-value pairs within an object
indent = indent ? indent+' ':' '; // every level should be indented 2 spaces more
if (typeof obj !== 'object') { // if it's a simple value (not obj or array)
return [indent, obj, '\n'].join('');// add it to the string (with a new line at the end)
} else { // otherwise
var ret = '';
for (var key in obj) { // loop through the object
if (obj.hasOwnProperty(key)) { // check if the key refers to one of its values (and not the prototype)
// if yes add the "key: " + the result objs2String(value) with correct indentation
ret += [indent, key+':\n', obj2String(obj[key], indent)].join('');
}
}
return (obj.indexOf ? // return the results wrapped in a [] or {} depending on if it's an object or array (by checking the indexOf method. of course this delivers false results if the object has an indexOf method)
[indent, '[\n', ret, indent, ']']:[indent, '{\n', ret, indent, '}']).join('');
}
}
console.log(obj2String(jsonObj)); // print out the result