简体   繁体   中英

Get nested key by name

I have this structure:

const config = { modules: [ { debug: true }, { test: false } ] }

And I want a function that gives me the status of a module. For example:

getStatus("debug")

With config["modules"] I get the array, but how do I return the value of a specific key in the nested objects?

config["modules"][0] would return debug: true and config["modules"][1] would return test: false

How do I search for a key of an numbered index?

You can call it like an object config["modules"] [0]["debug"]

If you don't know the index you can filter the array and return the first one where debug is not undefined

var y = config["modules"].filter(x => x["debug"] != undefined)
return y[0]["debug" ]

Bracket notation helps to reference object keys using a declared variable.

Assuming:

const config = { modules: [ { debug: true }, { test: false } ] }

This should work for your use case:

var getStatus = module => config.modules.filter(item => item.hasOwnProperty(module))[0][module];  
getStatus('debug'); // true
getStatus('test'); // false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM