将带有嵌套对象的JSON转换为JS中的列表数组 [英] Convert JSON with nested objects to list array in JS

查看:252
本文介绍了将带有嵌套对象的JSON转换为JS中的列表数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从JSON数据嵌套对象

How nested objects from JSON data

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

转换为这样的对象数组:

convert to array of objects like this:

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

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

level of nested objects may be different I try to solve it, but receive not what I need

推荐答案

使用递归:

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

这篇关于将带有嵌套对象的JSON转换为JS中的列表数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆