lodash-deep icon indicating copy to clipboard operation
lodash-deep copied to clipboard

New method: _.deepKeys

Open zaggino opened this issue 10 years ago • 0 comments

There're certainly situations where I could use this method:

var src = {
  "a": true,
  "b": {
    "ba": true,
    "bb": true
  }
}
var arr = _.deepKeys(src);
// returns ["a", "b.ba", "b.bb"]

This is my quick implementation which I needed:

function deepKeys(obj, path) {
  path = path || [];
  if (_.isArray(obj)) {
    path.push('0');
    obj = obj[0];
  }  
  return _.reduce(obj, function (result, value, key) {
    if (_.isPlainObject(value) || _.isArray(value)) {
      return result.concat(deepKeys(value, path.concat(key)));
    }
    result.push(path.concat(key).join("."));
    return result;
  }, []);
}

zaggino avatar May 08 '15 04:05 zaggino