Search code examples
javascriptangularlodash

Avoid getting array indexes via traversing through JSON object


METHOD : -

const getAllKeys = obj => _.union(
  _.keys(obj),
  _.flatMap(obj, o => _.isObject(o) ? getAllKeys(o) : [])
)

SAMPLE JSON :-

const arr = {"{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}}

const result = getAllKeys(arr)
console.log(result);

Result : -

["0", "1", "name", "url"]

Where in the result set I need to avoid getting array index which is "0"and "1" Any idea on how to make it possible? I only need the distinct key without array indexes.

Language : Angular 4 + lodash + javascript


Solution

  • Using _.keys()

    const arr = [{"name":"Base Url","url":"https://kubemanagement-prod.kohls.com"},{"name":"Base Url newwww","url":"https://batman.com"}]
    
    const getAllKeys = obj => _.uniq(
      _.flatMap(obj, o => _.isObject(o) ? _.keys(o) : [])
    )
    
    console.log(getAllKeys(arr))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>