Adirtha1704
Adirtha1704

Reputation: 359

How do I get the value of a key from a list of objects in Javascript?

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

Answers (4)

baao
baao

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

dezfowler
dezfowler

Reputation: 1268

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

Upvotes: -1

Code Maniac
Code Maniac

Reputation: 37775

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

Upvotes: 0

Maheer Ali
Maheer Ali

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

Related Questions