所以我们有一个示例 json
{
"name": "app",
"version": "0.1.0",
"description": "Sample description",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "some git url"
},
"keywords": [
"node"
],
"author": "Anonymous",
"license": "ISC"
}
这是我们的 node.js 脚本
var obj = require('./package.json');
console.log(obj[process.argv[2]]);
当我执行时node getval.js version
, 有用。但是,当我执行node getval.js repository.url
,我变得不确定。
当我将代码更改为下面的代码时,它就起作用了。但是,我不想对键值进行硬编码
console.log(obj['repository']['url']);
给定一个对象obj
and a "repository.url"
key
,你可以获得深度值
var val = key.split(".").reduce((o,k)=>o[k],obj);
示范:
var obj = {
"name": "app",
"version": "0.1.0",
"description": "Sample description",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "some git url"
},
"keywords": [
"node"
],
"author": "Anonymous",
"license": "ISC"
};
var key = "repository.url";
var val = key.split(".").reduce((o,k)=>o[k],obj);
document.write("result: \"" + val + "\"");
现在,假设您想要一些在缺少某些属性时不会引发异常的东西,例如"repository.language.version"
,那么你可以做
var val = key.split(".").reduce((o={},k)=>o[k],obj);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)