Search code examples
javascriptjsonnode.jsjavascript-objects

Access elements inside json object without knowing names


I have the following json object in node.js.

x={
    '40': {
        length: '2',
        data: ['11', '22']
    },
    '41': {
        length: '1',
        data: ['fe']
    },
    '42': {
        length: '2',
        data: ['ef', 'ab']
    },  
}

Suppose I do not know in advance what will be the property name inside x. However, I would like to retrieve every property and its associated value. How can this be done?

I am using node.js


Solution

  • Use recursion to find the key/values of all objects nested or otherwise:

    function finder(obj) {
    
      // for each property in the object passed into
      // the function...
      for (var p in obj) {
    
        // if its value is another object (see appended note)...
        if (Object.prototype.toString.call(obj[p]).slice(8, -1) === 'Object') {
    
          // ...log the key to the console and then call finder()
          // again with this current object (this is the recursive part)
          console.log('key: ' + p + ', value: Object');
          finder(obj[p]);
    
        // otherwise log the key/value
        } else {
          console.log('key: ' + p + ', value: ', obj[p]);
        }
      }
    }
    
    finder(x);
    

    OUTPUT

    key: 40, value: Object
    key: length, value:  2
    key: data, value:  Array [ "11", "22" ]
    key: 41, value: Object
    key: length, value:  1
    key: data, value:  Array [ "fe" ]
    key: 42, value: Object
    key: length, value:  2
    key: data, value:  Array [ "ef", "ab" ]
    

    NOTE

    This rather long-winded line of code to check if a value is an object

    Object.prototype.toString.call(obj[p]).slice(8, -1) === 'Object'
    

    is necessary because typeof obj[p] === 'object' will return true for arrays and null too. It's a bit of a gotcha.

    Object.prototype.toString.call({})
    

    returns a string like "[object Object]", and the slice grabs the relevant section of the string.