Skip to content Skip to sidebar Skip to footer

Convert Json With Nested Objects To List Array In Js

How nested objects from JSON data { 'title': 'Sub sub cat', 'url': 'sub_sub_cat', 'parent': { 'title': 'Sub сat', 'url': 'sub_cat', 'parent': {

Solution 1:

Use recursion:

var original_data = {
    "title": "Sub sub cat",
    "url": "sub_sub_cat",
    "parent": {
      "title": "Sub сat",
      "url": "sub_cat",
      "parent": {
        "title": "Cat",
        "url": "cat",
      }
    }
};
/*
 * This first function creates an empty array, launches the recursion, and returns it
 */functionconvertData(data){
    var new_data = [];
    convertDataAux(data, new_data);
    return new_data;
}

/*
 * This one adds the relevant data to the array "n", recursively
 */functionconvertDataAux(d,n){
    if(d && d.title && d.url){ n.push({ title : d.title, url : d.url }); }
    Object.keys(d).forEach(function(key){
        if(key !== 'title' && key !== 'url'){
            convertDataAux(d[key],n);
        }
    });
}
// Now, just call the first functiondocument.body.innerHTML = JSON.stringify( convertData(original_data) );

Post a Comment for "Convert Json With Nested Objects To List Array In Js"