I have a list of objects in the following way:
obj = [ { a:[1,2,3] }, { b:[4,5,6] }, { c:[7,8,9] } ]
How do I get the correspoding array for a key using javascript?
Eg. For b, I would get [4,5,6]. I need a function where I can give the key as input and it returns me the corresponding array associated with it.
You can use find()
and Object.keys()
. Compare the first element of keys array to the given key.
const arr = [ { a:[1,2,3] }, { b:[4,5,6] }, { c:[7,8,9] } ];
const getByKey = (arr,key) => (arr.find(x => Object.keys(x)[0] === key) || {})[key]
console.log(getByKey(arr,'b'))
console.log(getByKey(arr,'c'))
console.log(getByKey(arr,'something'))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments