Search code examples
javascriptarraysobjectparent

Covert JS object into flat array with parent names


I have an object like this:

data:
{
    connection:
    {
        type: 0,
        connected: false
    },
    acceleration:
    {
        x: 0,
        y: 0,
        z: 0,
        watchId: 0,
        hasError: false
    }        
},

Converting it to flat array like this:

"connected": false
"hasError": false
"type": 0
"watchId": 0
"x": 0
"y": 0
"z": 0

is an easy task (recurrence is your friend!).

But is there any way in Javascript to get it with so called full parents, i.e. something like this:

"connection.connected": false
"acceleration.hasError": false
"connection.type": 0
"acceleration.watchId": 0
"acceleration.x": 0
"acceleration.y": 0
"acceleration.z": 0

Or am I expecting to much?


Solution

  • Another variant:

    function flatten(o) {
      var prefix = arguments[1] || "", out = arguments[2] || {}, name;
      for (name in o) {
        if (o.hasOwnProperty(name)) {
          typeof o[name] === "object" ? flatten(o[name], prefix + name + '.', out) : 
                                        out[prefix + name] = o[name];
        }
      }
      return out;
    }
    

    invoke like flatten(data);