Trang D
Trang D

Reputation: 327

How to fetch key of key object in JavaScript

I want to fetch the key of key from this object keys can be anything from time to time so i can not use specific key here is the data

{
        "test": {
            "4": [
                {
                some data
                }
            ]
        },
        "case": {
            "2": [
                {
                    some data
                },
                {
                    some data
                }
            ]
        }
    }

I have tried this to fetch it is fine but I want fetch only 2nd key, in example i just want to get key not complete object and the thing is i can not specifically mention the data like test or case it can be anything its dynamic.

let vv = _.get(obj,'test')
console.log(vv)
 {
            "4": [
                {
                some data
                }
            ]
        }

Upvotes: 1

Views: 407

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

You can create a function using lodash's _.flow(), that gets the part of the object, and extracts the keys:

const { flow, get, keys } = _

const getKeys = flow(
  get,
  keys
)

const obj = {
  "test": {
    "4": [{ d: 4 }]
  },
  "case": {
    "2": [{ d: 2 }, { d: 2 }]
  }
}


const result = getKeys(obj, 'test')

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Upvotes: 1

Related Questions