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

Viktor1903

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.

Maheer Ali

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I get a list of key, value pairs from the database for a select list in Yii?

how to get a list of key values from array of objects - JavaScript

How to get a key from array of objects by its value Javascript

How do I get list of only duplicate objects from a list

How do I get the neighboring keys and their value of a key from an object in javascript?

How do I just get a list of JSON objects from RestSharp?

How do I get a component from a ever changing List of objects?

How do I get the sum of specific attributes from objects in a list?

How do I get a key value of each object in a javascript object?

In python, how do I get the lowest key value pair in a list of objects/dicts where each item has a different, separate key value pair?

How do I get the color value from the List<Feature> list?

How do I get a value list from a tuple list?

How do I get a specific key value from JSON object

How do I get the value for a key from a const ref?

How do I get a key from a HashMap by providing the value?

How do I get a separate key and value from the resulting json?

How do I get Enum key from a value in Typescript?

How do I fetch the value from a key in firebase using javascript

For a list containing dictionary objects, how do I filter the list based on the value of a key?

How do I return the difference between a list of dictionaries and a list of objects based on a specific key:value only

Given an array of objects, how do I replace the key name with another whilst keeping the value from the original key?

How do I get the full value(including any additional tags) from .text of an XML key / Value using Javascript

How do I get a list of webapi objects?

How do i get the value from my drop down list

How can i do a list of objects in javascript?

How to get dictionary value from key in a list?

How do I add key randomly from a list and value from another list but on the same index number in a dictionary?

How to get list of objects from list of jobjects based on key exists or not?

Can I get each value based on key from array of objects?