Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print object that matches value in an array

I have an the following array of items:

[
{
  url: "www.google.com",
  name: "name1"
},
{
  url: "www.google.com2",
  name: "name1"
},
{
  url: "www.google.com3",
  name: "name1"
}
]

and a variable:

let url = "www.google.com2"

How would I check if the variable exists in the array, and if it exists, how would I print the specific object that marches the variable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am able to check if the variable exists in the array, but how would I print the specific object that has the same url as the variable?

>Solution :

  • you can loop though an array via forEach method
  • and add if condition to check if url is matching and inside condition console log entire(found) object
const input = [
{
url: "www.google.com",
name: "name1"
},
{
url: "www.google.com2",
name: "name1"
},
{
url: "www.google.com3",
name: "name1"
}
]


let url = "www.google.com2"

input.forEach(object => {
  if(object.url === url) {
  console.log(object)
  }
})
  • or if would like to find only one element in the array

  • you can use find method

  • also you can store found element in the variable

const input = [
{
url: "www.google.com",
name: "name1"
},
{
url: "www.google.com2",
name: "name1"
},
{
url: "www.google.com3",
name: "name1"
}
]


let url = "www.google.com2"

const foundObject = input.find(object => object.url === url)

console.log('foundObject', foundObject)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading