最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How do I get the value of a key from a list of objects in Javascript? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question asked Jul 25, 2019 at 20:01 Adirtha1704Adirtha1704 3591 gold badge4 silver badges19 bronze badges 7
  • 2 Can you show us what have you tried so far? – Shidersz 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]}? – Daniel Beck Commented Jul 25, 2019 at 20:04
  • Actually this is a return I get from an api call and the data es in this format. – Adirtha1704 Commented Jul 25, 2019 at 20:04
  • 1 Possible duplicate of Find object by id in an array of JavaScript objects – str Commented Jul 25, 2019 at 20:06
  • @str Not exactly the same question that – Adirtha1704 Commented Jul 25, 2019 at 20:11
 |  Show 2 more ments

4 Answers 4

Reset to default 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'))

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

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

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

发布评论

评论列表(0)

  1. 暂无评论