Javascript reflection: Get nested objects path

前端 未结 3 625
感情败类
感情败类 2021-01-03 02:35

In this stackoverflow thread, i learnt you can get a object path via a simple string.

Accessing nested JavaScript objects with string key

consider the follow

3条回答
  •  攒了一身酷
    2021-01-03 03:24

    This is what worked for me. Note that, a raw map is created first and then mapped to an join the items in the Array with ..

    var toIterate = {
      name: "somename",
      personal: {
        age: "19",
        color: "dark"
      }
    };
    
    console.log(getObjPath(toIterate).map(item => item.join('.')));
    
    function isObject(x) {
      return Object.prototype.toString.call(x) === '[object Object]';
    };
    
    function getObjPath(obj, pathArray, busArray) {
      pathArray = pathArray ? pathArray : [];
      if (isObject(obj)) {
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (isObject(obj[key])) {
              busArray = busArray ? bussArray : [];
              busArray.push(key);
              getObjPath(obj[key], pathArray, busArray);
            } else {
              if (busArray) {
                pathArray.push(busArray.concat([key]));
              } else {
                pathArray.push([key]);
              }
            }
          }
        }
      }
      return pathArray;
    }

    Good Luck...

提交回复
热议问题