在javascript中对嵌套的json数组对象进行排序

时间:2011-08-26 05:43:49

标签: javascript arrays json sorting nested

var dataSource = ({
"Items": ({
    "Deserts": ({}),
    "Veg": ({
        "VegPulao": "Veg Pulao",
        "PalakPaneer": "Palak Paneer",
        "PaneerButterMasala": "Paneer Butter Masala"
    }),

    "Chicken": ({
        "Tandoori": "Tandoori special"
    }),
    "Hot drinks": ({
        "Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
        "Tea": ({ "Red": "Red Tea", "Black": "Black Tea" }),
        "Hot BadamMilk": "Hot Badam Milk",
        "Hot Bornvita": "Hot Bornvita",
        "Hot Milk": "Hot Milk"
    }),
    "Juice": ({
        "Mango": "Mango",
        "Berry": "Berry",
        "Grapes": "Grapes",
        "Wine": ({
            "Rose": "Rose",
            "Red wine": "Red",
            "Apple": "Apple",
            "Hard drinks": ({
                "Royal challenge": "Royal challenge",
                "Blender's Pride": "Blender's Pride"
            })
        })
    })
})

});

需要对嵌套的json对象进行排序 像上面那个?

1 个答案:

答案 0 :(得分:1)

您现在可能已经找到答案了,

function rFun(obj, newObj){
    Object.keys(obj).sort().forEach(key=>{
        if(typeof obj[key] === 'object'){
            newObj[key] = {};
            newObj[key] = rFun(obj[key], newObj[key]);
        } else {
            newObj[key] = obj[key];
        }
    });
    return newObj;
}

JSON.stringify(rFun(dataSource, {}));

它是按ASCII排序的,为了不区分大小写,您必须编写自定义排序。