Ray Saudlach
Ray Saudlach

Reputation: 650

TypeScript: Find Key Value in Object

I have an object like

const myObj = {
  policy : {
            title: "policy title",
            page : "/pageOne"
         },
  purchase : {
            title: "purchase title",
            page : "/pageTwo"
         }
}

I need to search through this object and find where page is "/pageTwo" and return not just the title but also the key (ie purchase)

Is there a simple way to do this in TS?

Upvotes: 0

Views: 61

Answers (1)

Lauren Yim
Lauren Yim

Reputation: 14078

Try this:

const myObj = {
  policy: {
    title: "policy title",
    page: "/pageOne"
  },
  purchase: {
    title: "purchase title",
    page: "/pageTwo"
  }
}

const found = Object.entries(myObj).find(([, {page}]) => page === "/pageTwo")
console.log(found)

Object.entries returns an array of [key, value] pairs, so Object.entries(myObj) would be

[
  ["policy", {title: "policy title", page: "/pageOne"}],
  ["purchase", {title: "purchase title", page: "/pageTwo"}]
]

Then, find the entry where the value's page property is "/pageTwo" using find.

Upvotes: 3

Related Questions