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.

7
  • 2
    Can you show us what have you tried so far? 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]}? Commented Jul 25, 2019 at 20:04
  • Actually this is a return I get from an api call and the data comes in this format. Commented Jul 25, 2019 at 20:04
  • 1
    Possible duplicate of Find object by id in an array of JavaScript objects Commented Jul 25, 2019 at 20:06
  • @str Not exactly the same question that Commented Jul 25, 2019 at 20:11

4 Answers 4

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'))

Sign up to request clarification or add additional context in comments.

Comments

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'))

1 Comment

That may cause unwanted sideeffects and false trues. stackoverflow.com/questions/455338/…
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'));

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.