3

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.

Viktor1903
  • 359
  • 1
  • 4
  • 18
  • 2
    Can you show us what have you tried so far? – Shidersz Jul 25 '19 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 Jul 25 '19 at 20:04
  • Actually this is a return I get from an api call and the data comes in this format. – Viktor1903 Jul 25 '19 at 20:04
  • 1
    Possible duplicate of [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – str Jul 25 '19 at 20:06
  • @str Not exactly the same question that – Viktor1903 Jul 25 '19 at 20:11
  • No not exactly the same, but close enough to qualify as a duplicate. And I'm sure if you searched a little longer than I did, you would have found an exact duplicate. Some effort from your side is expected. – str Jul 25 '19 at 20:15
  • I could not relate it to my question. Hence I posted a question. I have been trying to get this right for a long time. – Viktor1903 Jul 25 '19 at 20:17

4 Answers4

2

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'))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

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'))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 1
    That may cause unwanted sideeffects and false trues. https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript – baao Jul 25 '19 at 20:11
0

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'));
baao
  • 71,625
  • 17
  • 143
  • 203
-1

Just use a property indexer i.e. obj['b']

dezfowler
  • 1,238
  • 10
  • 20