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.
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.
Share Improve this question asked Jul 25, 2019 at 20:01 Adirtha1704Adirtha1704 3591 gold badge4 silver badges19 bronze badges 7- 2 Can you show us what have you tried so far? – Shidersz Commented Jul 25, 2019 at 20:03
-
This is a strange and somewhat inconvenient data structure. Is there a reason you're using an array of separate objects each with a unique key name, instead of just a single object like
obj = {a: [1,2,3], b: [4,5,6], c: [7,8,9]}
? – Daniel Beck Commented Jul 25, 2019 at 20:04 - Actually this is a return I get from an api call and the data es in this format. – Adirtha1704 Commented Jul 25, 2019 at 20:04
- 1 Possible duplicate of Find object by id in an array of JavaScript objects – str Commented Jul 25, 2019 at 20:06
- @str Not exactly the same question that – Adirtha1704 Commented Jul 25, 2019 at 20:11
4 Answers
Reset to default 2You 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'))
You can use find
and in
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'))
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'));
Just use a property indexer i.e. obj['b']