js 输入 dependency tree(依赖树?),输出版本,如何做?

输入一个多级对象,输出一个数组

输入 一个依赖树 如下

  var loremIpsum = {
  "name": "lorem-ipsum",
  "version": "0.1.1",
  "dependencies": {
    "optimist": {
      "version": "0.3.7",
      "dependencies": {
        "wordwrap": {
          "version": "0.0.2"
        }
      }
    },
    "inflection": {
      "version": "1.2.6"
    }
  }
}

输出版本号

 [ 'inflection@1.2.6', 'optimist@0.3.7', 'wordwrap@0.0.2' ]

Dependencies should be printed as dependency@version e.g. 'inflection@1.2.6'.

阅读 2.5k
2 个回答
var loremIpsum = {
  "name": "lorem-ipsum",
  "version": "0.1.1",
  "dependencies": {
    "optimist": {
      "version": "0.3.7",
      "dependencies": {
        "wordwrap": {
          "version": "0.0.2"
        }
      }
    },
    "inflection": {
      "version": "1.2.6"
    }
  }
}

var versions = [];

function dfs(key, obj) {
    if(typeof obj == 'object') {
        for(var k in obj) {
            if(k == 'version' && key) {
                versions[versions.length] = (key + '@' + obj[k]);
            } else if(typeof[obj[k]] == 'object') {
                arguments.callee(k, obj[k]);
            }
        }
    }
}

dfs('', loremIpsum);

console.log(versions);


多级都可以
        var loremIpsum = {
          "name": "lorem-ipsum",
          "version": "0.1.1",
          "dependencies": {
            "optimist": {
              "version": "0.3.7",
              "dependencies": {
                "wordwrap": {
                  "version": "0.0.2"
                }
              }
            },
            "inflection": {
              "version": "1.2.6"
            }
          }
        }

        var dependencies = loremIpsum.dependencies;

        var versions = [];

        function loopVersion(object){
            for(var key in object){

                var prevObject = object;
                var prevKey = key;

                if(typeof object[key] == 'object'){
                    for(var prop in object[key]){
                        if(prop == 'version'){
                            versions.push(prevKey + '@' + object[key][prop]);
                        }
                        if(typeof object[key][prop] == 'object'){
                            loopVersion(object[key][prop]);
                        }
                    }
                }
                
            }
        }

        loopVersion(dependencies);

        console.log(versions)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏