0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.