Reputation: 359
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.
Upvotes: 3
Views: 14474
Reputation: 73301
You can use find
and hasOwnProperty
const arr = [ { a:[1,2,3] }, { b:[4,5,6] }, { c:[7,8,9] } ];
const byKey = (arr, key) => {
return (arr.find(e => e.hasOwnProperty(key)) || {})[key];
};
console.log(byKey(arr, 'a'));
Upvotes: 0
Reputation: 37775
let obj = [ { a:[1,2,3] }, { b:[4,5,6] }, { c:[7,8,9] } ]
let findByKey = (arr,key) => {
return (arr.find(ele=> key in ele ) || {})[key]
}
console.log(findByKey(obj,'b'))
console.log(findByKey(obj,'xyz'))
Upvotes: 0
Reputation: 36594
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'))
Upvotes: 2