【发布时间】:2021-09-10 04:54:40
【问题描述】:
我正在用 JavaScript 编写一个程序,它将遍历嵌套的 JSON schema,我希望它返回给定 schema key 的 Paths 和 Values 的元组列表
这是我的示例数据
var data = {"a":"hello",
"b":{"a":"world"},
"c":[{"a":"Good"},{"d":"Morning"}]}
我希望我的程序返回给定键 a
[(['a'],'hello'),(['b','a'],'world'),(['c',0,'a'],'Good')]
下面是我的脚本,目前它返回values 的key 'a' [ 'hello', 'world', 'Good' ]。我也可以控制台Paths,但无法以上述格式返回Paths 和values .
var _ = require('lodash');
function _generate_values(data, key,path){
if (Array.isArray(data)) {
return _.map(data,function(x, idx){
return _generate_values(x, key,path.concat([idx]))
}
)
}else if(typeof data==="object"){
return _.map(
_.keys(data),
function(x){
if(x===key){
console.log(path.concat(x)) // consoles paths ['a'],['b','a'],['c',0,'a']
return _.get(data,x) // returns [ 'hello', 'world', 'Good' ]
}else{
return _generate_values(_.get(data, x), key,path.concat([x]))
}
}
)
}else{
return null
}
}
function find_values_(data, key, paths =false)
{
return( _.chain(_generate_values(data, key,[]))
.flattenDeep()
.compact()
.value()
)
}
console.log(find_values_(data,'a'))
【问题讨论】:
标签: javascript node.js lodash