rubalvjaiswal
rubalvjaiswal

Reputation: 177

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

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}
]

Upvotes: 2

Views: 57

Answers (2)

ABDULLOKH MUKHAMMADJONOV
ABDULLOKH MUKHAMMADJONOV

Reputation: 5234

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

Upvotes: 0

Aghil Varghese
Aghil Varghese

Reputation: 400

I hope this piece of code will help you

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

Upvotes: 1

Related Questions