Last active
February 5, 2017 12:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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