所以我们有一个示例 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
时,我得到了 undefined。
当我将代码更改为下面的代码时,它起作用了。但是,我不想对键值进行硬编码
console.log(obj['repository']['url']);
最佳答案
给定一个对象obj
和一个"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);
关于javascript - 在不使用 lodash get 的情况下从 json 中提取深层属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192518/