Skip to content

Instantly share code, notes, and snippets.

@rbrahul
Last active February 5, 2017 12:54
Show Gist options
  • Save rbrahul/643333121fe333adf4896016be7a8b47 to your computer and use it in GitHub Desktop.
Save rbrahul/643333121fe333adf4896016be7a8b47 to your computer and use it in GitHub Desktop.
This script finds the last child node in any tree like object implementing recursion in javascript
const data = {
first: {
second: {
user: {
name:'Rahul',
title: 'Baruri'
},
third: {
info: {
salary: 70000,
age: 27,
skillset: {
"java": {score:70,
status: 'novice'
}
}
}
}
},
second1: ['Ripan'],
second3: {
salary: 70000,
age: 27,
skillset: {
"java": {
score:70,
status: 'final'
}
}
}
},
second: {
name: 'Sourav'
},
third: {
name: 'Roni',
condes: {
"java": {
score:70,
status: ['java','c#','kotlin']
}
}
}
}
function getlastNode(data) {
if (typeof data === 'object' && data instanceof Array === false){
const properties = Object.keys(data);
const newNode = data[properties[properties.length-1]];
return getlastNode(newNode);
} else {
return data;
}
}
console.log("Last child node: "+getlastNode(data)+"\n\n");
let lastNodes = [];
Object.keys(data).forEach((key, index) => {
lastNodes.push(getlastNode(data[key]));
});
console.log("All last nodes: ")
console.log(lastNodes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment