keys.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var baseHas = require('./_baseHas'),
  2. baseKeys = require('./_baseKeys'),
  3. indexKeys = require('./_indexKeys'),
  4. isArrayLike = require('./isArrayLike'),
  5. isIndex = require('./_isIndex'),
  6. isPrototype = require('./_isPrototype');
  7. /**
  8. * Creates an array of the own enumerable property names of `object`.
  9. *
  10. * **Note:** Non-object values are coerced to objects. See the
  11. * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
  12. * for more details.
  13. *
  14. * @static
  15. * @since 0.1.0
  16. * @memberOf _
  17. * @category Object
  18. * @param {Object} object The object to query.
  19. * @returns {Array} Returns the array of property names.
  20. * @example
  21. *
  22. * function Foo() {
  23. * this.a = 1;
  24. * this.b = 2;
  25. * }
  26. *
  27. * Foo.prototype.c = 3;
  28. *
  29. * _.keys(new Foo);
  30. * // => ['a', 'b'] (iteration order is not guaranteed)
  31. *
  32. * _.keys('hi');
  33. * // => ['0', '1']
  34. */
  35. function keys(object) {
  36. var isProto = isPrototype(object);
  37. if (!(isProto || isArrayLike(object))) {
  38. return baseKeys(object);
  39. }
  40. var indexes = indexKeys(object),
  41. skipIndexes = !!indexes,
  42. result = indexes || [],
  43. length = result.length;
  44. for (var key in object) {
  45. if (baseHas(object, key) &&
  46. !(skipIndexes && (key == 'length' || isIndex(key, length))) &&
  47. !(isProto && key == 'constructor')) {
  48. result.push(key);
  49. }
  50. }
  51. return result;
  52. }
  53. module.exports = keys;