how to access a property of an object, if the property name is not fully known?

Viewed 49

How to access a property of a javascript object if property name is not fully known? Need to access value by knowing that "totalCount" will be part of property name. Sample :

[
  {"totalCount_12":100},
  {"totalCount_13":100},
  {"totalCount_2":100}
]
2 Answers

I hope this piece of code will help you

a = {"totalCount_12":100}
a[Object.keys(a).filter(i=>i.includes("totalCount"))[0]]

You can achieve this by creating a special function that finds 'totalCount_'+n (n is a given number)

const list = [
  {"totalCount_12":75},
  {"totalCount_13":100},
  {"totalCount_2":150},
  {"totalCount_14":17}
]

const findByPartlyKnownName = (n) => list.find(el => Object.keys(el)[0].includes(`totalCount_${n}`))

console.log(findByPartlyKnownName(12))
console.log(findByPartlyKnownName(14))
console.log(findByPartlyKnownName(2))
Related