Question

I am looking for a technique to run over a object of nested properties and wish to join the properties'.

This is the object I'd like to join:

var array = {
  prop1: {
    foo: function() {
      // Your code here
    }
  },
  prop2: {
    bar1: 'some value',
    bar2: 'some other value'
  }
};

The result should look like this:

[
  [ 'prop1', 'foo' ],
  [ 'prop2', 'bar1' ],
  [ 'prop2', 'bar2' ]
]

Then I'd like to join the array to strings formatted like this:

prop1.foo
prop2.bar1
prop2.bar2

Any tips?

EDIT: Forgot to say it should work for deeper arrays too.

No correct solution

OTHER TIPS

Something along these lines? http://jsfiddle.net/X2X2b/

var array = {
  prop1: {
    foo: function() {
      // Your code here
    }
  },
  prop2: {
    bar1: 'some value',
    bar2: 'some other value'
  }
};

var newA = [],
    newB = [];
for  ( var obj in array ) {
    for  (var inObj in array[obj]) {
        newA.push([obj, inObj]);
        newB.push(obj + '.' + inObj);
    }
}

console.log(newA);
console.log(newB);

This is quite a different problem now that you have specified that it needs to support arbitrary depths. In order to solve it we need to use recursion and we need to use a second recursive parameter which keeps track of where we are in the nested hierarchy.

function objectPropertiesToArrays(obj, prepend) {
  // result will store the final list of arrays
  var result = [];

  // test to see if this is a valid object (code defensively)
  if(obj != null && obj.constructor === Object) {
    for (var propertyName in obj) {
      var property = obj[propertyName],
          // clone prepend instantiate a new array
          list = (prepend || []).slice(0);

      // add the property name to the list
      list.push(propertyName);

      // if it isn't a nested object, we're done
      if (property.constructor !== Object) {
        result.push(list);

      // if it is a nested object, recurse
      } else {
        // recurse and append the resulting arrays to our list
        result = result.concat(objectPropertiesToArrays(property, list));
      }
    }  
  }    

  return result;
}

Example:

var obj = {  
  prop1: {
    foo: function() { }
  },
  prop2: {
    bar1: 'some value',
    bar2: 'some other value'
  },
  prop3: {
    x: {
      y: [],
      z: 'test'
    },
    erg: 'yar'
  }
};

objectPropertiesToArrays(obj);

Returns

[
  ["prop1", "foo"],
  ["prop2", "bar1"],
  ["prop2", "bar2"],
  ["prop3", "x", "y"],
  ["prop3", "x", "z"],
  ["prop3", "erg"]
]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top