Skip to content

Instantly share code, notes, and snippets.

@sranka23
Last active September 9, 2021 13:00
Show Gist options
  • Save sranka23/e139462f937c50dfe7ffc30731df14f1 to your computer and use it in GitHub Desktop.
Save sranka23/e139462f937c50dfe7ffc30731df14f1 to your computer and use it in GitHub Desktop.
Object Builder (arrayToObjectParser) : Provided an array of strings, the program returns an output object with key in correct hierarchy.
/*
Author: Shourya Ranka
Objective : Provided an array of strings, the program returns an output object with key in correct hierarchy.
input : ["root", "root.user", "root.user.a", "root.a"]
output : {
root: {
a:{},
user:{
a:{}
}
}
}
*/
const arrayToObjectParser = (arrayInput) => {
if(!arrayInput || !arrayInput.length){
return {};
}
let result = {};
arrayInput.forEach(function(item, index){
let itemsList = item.split(".");
if(itemsList.length > 1){
result[itemsList[0]] = result[itemsList[0]] || {};
let pointer = result[itemsList[0]];
for(let i=1; i<itemsList.length;i++){
pointer[itemsList[i]] = {};
pointer = pointer[itemsList[i]];
}
}
else{
result[item] = {};
}
});
return result;
}
// Test 1 : Ideal case input
console.log(arrayToObjectParser(["root", "root.user", "root.user.a", "root.a"]));
// Test 2 : Input is empty
console.log(arrayToObjectParser([]));
// Test 3 : Input is invalid
console.log(arrayToObjectParser());
// Test 4 : Parent item is not provided
console.log(arrayToObjectParser(["root.user", "root.user.a", "root.a"]));
// Test 5 : Only nested key is provided
console.log(arrayToObjectParser(["root.user.a"]));
@sranka23
Copy link
Author

sranka23 commented Sep 9, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment