Small libary to retrieve keys of a JSON object or array.
Install via npm
npm install @barreljs/json-keys
or yarn
yarn add @barreljs/json-keys
const JsonKeys = require('@barreljs/json-keys')
Returns all keys as an array of strings
const keys = JsonKeys.keys({
key: 'value',
obj: {
key: 'value'
}
})
returns
['key', 'obj', 'key']
Returns all unique keys as an array of strings
const keys = JsonKeys.uniqueKeys({
key: 'value',
obj: {
key: 'value'
}
})
returns
['key', 'obj']
Returns all keys including their path in dot notation as an array of strings
const paths = JsonKeys.paths({
key: 'value',
obj: {
key: 'value'
},
arr: [
{
key: 'value'
}
]
})
returns
['key', 'obj', 'obj.key', 'arr', 'arr.0', 'arr.0.key']
checks if a path (or sub-path) in dot notation is part of a JSON object.
// returns true
JsonKeys.hasKey({
key: 'value',
obj: {
key: 'value'
},
arr: [
{
key: 'value'
}
]
}, '0.key')
// returns false
JsonKeys.hasKey({
key: 'value',
obj: {
key: 'value'
},
arr: [
{
key: 'value'
}
]
}, 'tree.doesNotExist')
This project is licensed under the MIT license, Copyright (c) 2020 David Pichsenmeister | pichsenmeister.com. For more information see LICENSE.