[英]sort a nested json array object in javascript
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"
})
})
})
})
});
Need to sort a nested json object like the one above? 是否需要对上述嵌套json对象进行排序?
You might have got the answer by now, 您可能现在已经得到了答案,
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, {}));
it's sort by ASCII, for case insensitive you have to write custom sort. 它是按ASCII排序的,如果不区分大小写,则必须编写自定义排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.