0

I am writing a function in node js which accepts 2 parameter - "param1" is "jsonObj" & "param2" is "xpath"(as String) but when I am trying to extract the value using jsonObj.xpath I am getting result as undefined as it is looking for xpath as a key in the json object rather than cDel.dInfo.env. Can someone please let me know how to extract the value of cDel.dInfo.env from jsonObj.

Below is the sample code -

const json = '{ "cDel": { "dInfo": { "env": "ACCEPTANCE", "ref": 103163 } } }';
const obj = JSON.parse(json);

var getValue = (jsonObj,xpath) => {
       return jsonObj.xpath;
}

console.log(getValue(obj,"cDel.dInfo.env"));

Output is undefined. Expected Output is ACCEPTANCE.

2 Answers 2

1

You can use Lodash's get()

var object = { 'a': [{ 'b': { 'c': 3 } }] };
 
_.get(object, 'a[0].b.c');
// => 3
 
_.get(object, ['a', '0', 'b', 'c']);
// => 3
 
_.get(object, 'a.b.c', 'default');
// => 'default'
Sign up to request clarification or add additional context in comments.

3 Comments

I would also recommend lodash rather than reinventing the wheel if you aren't already using it.
If you only want get from Lodash, use npmjs.com/package/lodash.get
Thanks for the response. Lodash worked fine for me.
1

That's not how it works. Every property from xpath must be read separately. Something like:

const obj = JSON.parse('{ "cDel": { "dInfo": { "env": "ACCEPTANCE", "ref": 103163 } } }');
const getValue = (jsonObj, xpath) => {
  const path = xpath.split(".");
  let value = jsonObj;
  
  while (path.length) {
    value = value[path.shift()];
  }
  return value;
}

console.log(`obj.cDel.dInfo.env => ${getValue(obj, "cDel.dInfo.env")}`);

2 Comments

Thanks for the response. Above code will work fine for json with no array. Since I want write generic function I think lodash suites my requirement.
Your question did not mention an array within the json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.