Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the path from javascript object from key and value

I have a javascript object width depth.

I need to know the exact path from this key within the object ex: "obj1.obj2.data1"

I already know the key is data1, the value is 123.

My javascript object look like this

{
    obj1: {
        obj2: {
            data1: 213,
            data2: "1231",
            obj3: {
                data: "milf"
            }
        }
    },
    obj4: {
        description: "toto"
    }
}

How could I achieve that ?

here is a jsfiddle : http://jsfiddle.net/3hvav8xf/8/ I am trying to implement getPath.

like image 438
Dimitri Kopriwa Avatar asked Aug 20 '14 11:08

Dimitri Kopriwa


2 Answers

I think recursive function can help to you (Updated version, to check value)

function path(c, name, v, currentPath, t){
    var currentPath = currentPath || "root";

    for(var i in c){
      if(i == name && c[i] == v){
        t = currentPath;
      }
      else if(typeof c[i] == "object"){
        return path(c[i], name, v, currentPath + "." + i);
      }
    }

    return t + "." + name;
};

console.log(path({1: 2, s: 5, 2: {3: {2: {s: 1, p: 2}}}}, "s", 1));
like image 87
Farkhat Mikhalko Avatar answered Oct 16 '22 20:10

Farkhat Mikhalko


I ended up with the following function, that works with nested objects/arrays :

function findPath (obj, name, val, currentPath) {
  currentPath = currentPath || ''

  let matchingPath

  if (!obj || typeof obj !== 'object') return

  if (obj[name] === val) return `${currentPath}['${name}']`

  for (const key of Object.keys(obj)) {
    if (key === name && obj[key] === val) {
      matchingPath = currentPath
    } else {
      matchingPath = findPath(obj[key], name, val, `${currentPath}['${key}']`)
    }

    if (matchingPath) break
  }

  return matchingPath
}

const treeData = [{
  id: 1,
  children: [{
    id: 2
  }]
}, {
  id: 3,
  children: [{
    id: 4,
    children: [{
      id: 5
    }]
  }]
}]

console.log(findPath (treeData, 'id', 5))
like image 27
David Chriqui Avatar answered Oct 16 '22 20:10

David Chriqui