Skip to content

Instantly share code, notes, and snippets.

@renso3x
Created August 8, 2017 05:28
Show Gist options
  • Save renso3x/0c8e8010a0fca281f0be7649a2f8dd72 to your computer and use it in GitHub Desktop.
Save renso3x/0c8e8010a0fca281f0be7649a2f8dd72 to your computer and use it in GitHub Desktop.
Flatten a nested object and sort by alphabetical order.
const obj = [
{
city: "Kampong Thom",
suburbs: [
{
suburb: "Stueng Saen",
suburbs: [
"Achar Leak",
"Damrei Choan Khla",
"Kampong Krabau",
"Kampong Roteh",
"Kampong Thum",
"Ou Kanthor",
"Prey Ta Hu",
"Srayov"
]
},
{
suburb: "Baray",
suburbs: [
"Andoung Pou",
"Bak Sna",
"Ballangk",
]
}
]
},
{
city: "Banteay Meanchey",
suburbs: [
{
suburb: "Malai",
suburbs: [
"Malai",
"Ou Sampor",
"Ou Sralau",
"Ta Kong",
"Tuol Pongro",
"boeung Beng"
]
}
]
},
{
city: "Phnom Penh",
suburbs: [
{ suburb: "7 Makara", suburbs: [] }
]
}
];
const flattenLoc = [];
function flatten(data) {
for (let city of data) {
const section = city.city.charAt(0);
const newSec = _.toInteger(section) ? '#' : section;
flattenLoc.push({
section: transformPascalCase(newSec),
label: city.city,
value: transformPascalCase(city.city),
});
for(let sub of city.suburbs) {
const section = sub.suburb.charAt(0);
const newSec = _.toInteger(section) ? '#' : section;
flattenLoc.push({
section: transformPascalCase(newSec),
label: sub.suburb,
value: transformPascalCase(sub.suburb),
});
for (let khan of sub.suburbs) {
const section = khan.charAt(0);
const newSec = _.toInteger(section) ? '#' : section;
flattenLoc.push({
section: transformPascalCase(newSec),
label: khan,
value: transformPascalCase(khan),
});
}
}
}
}
function transformPascalCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
flatten(obj);
const orderedLoc = _.orderBy(flattenLoc, ['label'], ['asc', 'desc']);
const sortByAlpha = _.groupBy(flattenLoc, 'section');
let sections = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z'];
// console.log(sortByAlpha);
const n = _.groupBy(orderedLoc, 'section')
console.log(n);
for (var i in n) {
console.log(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment