【问题标题】:How to return a similar Python list of tuple of list and string in JavaScript如何在 JavaScript 中返回一个类似的 Python 列表元组列表和字符串
【发布时间】:2021-09-10 04:54:40
【问题描述】:

我正在用 JavaScript 编写一个程序,它将遍历嵌套的 JSON schema,我希望它返回给定 schema keyPathsValues 的元组列表

这是我的示例数据

var data = {"a":"hello",
            "b":{"a":"world"},
            "c":[{"a":"Good"},{"d":"Morning"}]}

我希望我的程序返回给定键 a

 [(['a'],'hello'),(['b','a'],'world'),(['c',0,'a'],'Good')]

下面是我的脚本,目前它返回valueskey 'a' [ 'hello', 'world', 'Good' ]。我也可以控制台Paths,但无法以上述格式返回Pathsvalues .

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


    【解决方案1】:

    JavaScript 没有元组,但您可以返回一个 2 元素数组。

    return [path, _.get(data,x)]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2021-08-03
      相关资源
      最近更新 更多