[英]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? 如何使用javascript获取密钥的对应数组?
Eg. 例如。 For b, I would get [4,5,6]. 对于b,我将得到[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. 我需要一个函数,可以将键作为输入,并返回与之关联的对应数组。
You can use find()
and Object.keys()
. 您可以使用find()
和Object.keys()
。 Compare the first element of keys array to the given key. 将keys数组的第一个元素与给定键进行比较。
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 hasOwnProperty
您可以使用find
和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'));
只需使用属性索引器即obj['b']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.