Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var someObject = {
- 'part1' : {
- 'name': 'Part 1',
- 'txt': 'example',
- },
- 'part2' : {
- 'name': 'Part 2',
- 'size': '15',
- 'qty' : '60'
- },
- 'part3' : [
- {
- 'name': 'Part 3A',
- 'size': '10',
- 'qty' : '20'
- }, {
- 'name': '[value]',
- 'size': '5',
- 'qty' : '20'
- }, {
- 'name': 'Part 3C',
- 'size': '7.5',
- 'qty' : '20'
- }
- ]};
- getPath(obj, '[value]');
- function getPath(obj, val, path) {
- path = path || "";
- var fullpath = "";
- for (var b in obj) {
- if (obj[b] === val) {
- return (path + "/" + b);
- }
- else if (typeof obj[b] === "object") {
- fullpath = getPath(obj[b], val, path + "/" + b) || fullpath;
- }
- }
- return fullpath;
- }
- console.log(getPath(testObj, '20')); // Prints: /part3/2/qty
- console.log(getPath(testObj, "[value]")); // Prints: /part3/1/name
- function getPath(obj, value, path){
- path = path || [];
- if(obj instanceof Array || obj instanceof Object){
- //Search within children
- for(var i in obj){
- path.push(i); //push path, will be pop() if no found
- var subPath = getPath(obj[i], value, path);
- //We found nothing in children
- if(subPath instanceof Array){
- if(subPath.length == 1 && subPath[0]==i){
- path.pop();
- }
- //We found something in children
- }else if(subPath instanceof Object){
- path = subPath;
- break;
- }
- }
- }else{
- //Match ?
- if(obj == value){
- return {finalPath:path};
- }else{
- //not ->backtrack
- path.pop();
- return false;
- }
- }
- return path;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement