将嵌套对象的JSON转换为JS

时间:2015-07-17 13:57:45

标签: javascript json

JSON数据的嵌套对象

{
    "title": "Sub sub cat",
    "url": "sub_sub_cat",
    "parent": {
      "title": "Sub сat",
      "url": "sub_cat",
      "parent": {
        "title": "Cat",
        "url": "cat",
      }
    }
}

转换为这样的对象数组:

[   
    {"title": "Sub sub cat","url": "sub_sub_cat"},
    {"title": "Sub сat","url": "sub_cat"},
    {"title": "Cat","url": "cat"}
]

嵌套对象的级别可能不同 我尝试解决它,但receive不是我需要的

1 个答案:

答案 0 :(得分:0)

使用递归:

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
 */
function convertData(data){
    var new_data = [];
    convertDataAux(data, new_data);
    return new_data;
}

/*
 * This one adds the relevant data to the array "n", recursively
 */
function convertDataAux(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 function
document.body.innerHTML = JSON.stringify( convertData(original_data) );