Tengo una estructura JSON dinámica, por ejemplo:
{ "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate": { "numerator": 25, "denominator": 1 }, "specified": { "numerator": 1, "denominator": 1 }, "gop": { "length": 50, "reference_frames": 3, "sub_gop": "StaticType" }, "codec_details": { "profile": "Main", "level": "Level4", "entropy_encoding": "CABAC", "video_output": "AVC1" } } }Quiero transformarlo en un nodo de árbol.
export class TrackDetailsNode { key: string; value: string; children?: TrackDetailsNode[]; }Ejemplo de salida:
{ "key": "video", "children": [ { "key": "width", "value": "1920" }, { "key": "frameRate", "children": [ { "key": "numerator", "value": "60" }, { "key": "denominator", "value": "1" } ] } ] }Lo necesito de forma recursiva. Quiero construir un árbol a partir del JSON proporcionado. Intenté una solución múltiple, pero lleva mucho tiempo analizarla.
var obj = { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate": { "numerator": 25, "denominator": 1 }, "specified": { "numerator": 1, "denominator": 1 }, "gop": { "length": 50, "reference_frames": 3, "sub_gop": "StaticType" }, "codec_details": { "profile": "Main", "level": "Level4", "entropy_encoding": "CABAC", "video_output": "AVC1" } } }; function transform(data, output, children) { Object.keys(data).forEach((key) => { let value = data[key]; if (children) { if (typeof value === 'object') { const child = []; children.push({ 'key': key, children: child }); transform(value, undefined, child) } else { children.push({ 'key': key, value }) } } else { if (typeof value === 'object') { output.key = key; output.children = []; transform(value, undefined, output.children); } else { output.key = key; output.value = value; } } }); return output; } console.log(transform(obj, {})); const INPUT = { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate": { "numerator": 25, "denominator": 1 }, "specified": { "numerator": 1, "denominator": 1 }, "gop": { "length": 50, "reference_frames": 3, "sub_gop": "StaticType" }, "codec_details": { "profile": "Main", "level": "Level4", "entropy_encoding": "CABAC", "video_output": "AVC1" } } }; const isObject = (obj) => obj !== null && typeof obj === 'object'; const Transform = (input, isChildren) => { const output = isChildren ? [] : {}; if (input && isObject(input)) { Object.keys(input).forEach(key => { const value = input[key]; const val = isObject(value) ? Transform(value, true) : value; const valueKey = isObject(value) ? "children" : "value"; if (isChildren) { output.push({ "key": key, [valueKey]: val }); } else { output.key = key; output[valueKey] = val; } }) } return output; } const result = Transform(INPUT); console.log(JSON.stringify(result, null, 2));