0

If I having a nested JSON I wanted all the keys traversal path,

like for

var a={
     "a":"b",
     "c":{
     "d":"e"
      }
   }

const keyify = (obj, prefix = '') => 
  Object.keys(obj).reduce((res, el) => {
    if( Array.isArray(obj[el]) ) {
      return res;
    } else if( typeof obj[el] === 'object' && obj[el] !== null ) {
      return [...res, ...keyify(obj[el], prefix + el + '.')];
    } else {
      return [...res, prefix + el];
    }
  }, []);

const output = keyify(a);

console.log(output);

Output will be:

[ "a", "c.d" ]

In the above code it'll return all keys if it is not having object or array I means if it having string/integer/boolean. But for the below payload it is not giving any output.

var a=

    {
      "paramList": [
        {
          "parameterName": "temperature",
          "parameterpresentValue": "25.32",
          "parameterunits": "°C"
        },
        {
          "parameterName": "Pressure",
          "parameterpresentValue": "1004.08",
          "parameterunits": "mBar"
        }]
        }

Expected output:

["paramList.parameterName","paramList.parameterpresentValue","paramList.parameterunits"]
ashok
  • 1,078
  • 3
  • 20
  • 63
  • Possible duplicate of [Traverse all the Nodes of a JSON Object Tree with JavaScript](https://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript) – Heretic Monkey Sep 11 '19 at 20:02

1 Answers1

0

You are initializing the .reduce() with a blank array [], and then you have this line inside the callback:

.reduce((res, el) =>   // `res` is the accumulator array, `el` is the new element

  if( Array.isArray(obj[el]) ) {
    return res;
  }

Your first object, paramList is an array... so you return the blank [] that you initially passed. That's why you see no output. The code there is wrong

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • Tanks I got it, but can you suggest what changes I have to do for getting array result as I have given ["paramList.parameterName","paramList.parameterpresentValue","paramList.parameterunits"] – ashok Sep 11 '19 at 20:11
  • Did you try running `else if( typeof obj[el] === 'object' || Array.isArray(obj[el] ) {` condition? – Christopher Francisco Sep 11 '19 at 20:27