.deepKeys(..) -- added option to include non-enumerable keys.

Signed-off-by: Alex A. Naanou <alex.nanou@gmail.com>
This commit is contained in:
Alex A. Naanou 2022-05-30 10:51:26 +03:00
parent f02adb73b7
commit 2f26eda305
3 changed files with 31 additions and 5 deletions

View File

@ -183,19 +183,34 @@ function(strings, ...values){
// Get keys from prototype chain... // Get keys from prototype chain...
// //
// deepKeys(obj) // deepKeys(obj[, all])
// deepKeys(obj, stop) // deepKeys(obj, stop[, all])
// -> keys
//
// List all keys incuding non-enumerable...
// deepKeys(obj, true)
// deepKeys(obj, stop, true)
// -> keys // -> keys
// //
// //
// NOTE: this is like Object.keys(..) but will get keys for all levels // NOTE: this is like Object.keys(..) but will get keys for all levels
// till stop if given... // till stop if given...
// NOTE: by default this lists only enumerable keys...
var deepKeys = var deepKeys =
module.deepKeys = module.deepKeys =
function(obj, stop){ function(obj, stop, all){
all = arguments[arguments.length-1]
all = (all === true || all === false) ?
all
: false
stop = (stop === true || stop === false) ?
undefined
: stop
var res = [] var res = []
while(obj != null){ while(obj != null){
res.push(Object.keys(obj)) res.push(Object.keys(all ?
Object.getOwnPropertyDescriptors(obj)
: obj))
if(obj === stop){ if(obj === stop){
break } break }
obj = obj.__proto__ } obj = obj.__proto__ }

View File

@ -1,6 +1,6 @@
{ {
"name": "ig-object", "name": "ig-object",
"version": "5.5.7", "version": "5.6.0",
"description": "", "description": "",
"main": "object.js", "main": "object.js",
"scripts": { "scripts": {

11
test.js
View File

@ -684,10 +684,16 @@ var cases = test.Cases({
var a = { var a = {
a: true a: true
} }
var b = { var b = {
__proto__: a, __proto__: a,
b: true, b: true,
} }
Object.defineProperty(b, 'h', {
enumerable: false,
value: true,
})
var c = { var c = {
__proto__: b, __proto__: b,
c: true, c: true,
@ -698,6 +704,11 @@ var cases = test.Cases({
assert.array(object.deepKeys(c, b), ['c', 'b'], 'partial chain') assert.array(object.deepKeys(c, b), ['c', 'b'], 'partial chain')
assert.array(object.deepKeys(c, c), ['c'], 'partial chain') assert.array(object.deepKeys(c, c), ['c'], 'partial chain')
var o = Object.keys(Object.getOwnPropertyDescriptors(Object.prototype))
assert.array(object.deepKeys(c, true), ['c', 'b', 'h', 'a', ...o], 'full chain (non-enumerable)')
assert.array(object.deepKeys(c, a, true), ['c', 'b', 'h', 'a'], 'full chain (non-enumerable)')
assert.array(object.deepKeys(c, b, true), ['c', 'b', 'h'], 'partial chain (non-enumerable)')
assert.array(object.deepKeys(c, c, true), ['c'], 'partial chain (non-enumerable)')
}, },
funcMethods: function(assert){ funcMethods: function(assert){
var X = object.C('X', { var X = object.C('X', {