在NodeJs的console.log中打印JSONPath和值

时间:2018-12-06 05:53:55

标签: javascript node.js

我想在控制台中打印JSON路径, 例子

customer = {  
             "Name" : "Joe",
             "Address" : {
                          "Street" : "SomeStreet",
                          "City"   : "SomeCity"
                          }
            }

myfunction = function(myPath){
    console.log(myPath);
}

myfunction(customer.Address.City);
//This function should print "customer.Address.City" ( Not value "SomeCity")

1 个答案:

答案 0 :(得分:0)

您可以使用json路径获取值,在简单的代码段下面找到可以解决您问题的代码,尽管未在所有情况下进行测试。

const myfunction = function (myPath, customer) {
    const value = myPath.split(".").reduce((acc, cur) => {
        return acc[cur]
    }, customer)
    console.log('Path: ', myPath, ' Value: ', value)
}

const customer = {
    "Name": "Joe",
    "Address": {
        "Street": "SomeStreet",
        "City": "SomeCity"
    }
}
myfunction("Address.City", customer)

这里要注意的一件事是,您不应在json路径中添加变量名,这就是为什么我从json路径中跳过了 customer