timhc22
timhc22

Reputation: 7451

Is there a better/shorter way to check a value of an object within an array which is part of an object in Javascript?

I'm sure this question must have been answered before, so a link (or what specifically to ask Google) would suffice, but what is the best way to do a check in a scenario like this (and does the new ? operator help in scenarios like this):

/**
 * An API returns a job object like:
 * { id: 123, name: 'The Job', details: [ { detail_name: "Foo", some: "thing" }, { detail_name: "Bar", some: "thing else" } ] }
 */

const fooDetail = job.details.find(attr => {
  return attr.detail_name === 'Foo' });
        
if (fooDetail && fooDetail.detail_name === "Foo") {
  // todo process `some: "thing"` 
}

It seems long winded to have to find an object in an array based on a property, but then having to check again that the object exists before checking the property (or get a can't get detail_name of undefined error). Is there a better/shorter way?

Upvotes: 1

Views: 40

Answers (2)

svyat1s
svyat1s

Reputation: 943

You can do also

job.details.forEach(x=>{
    if(x.detail_name == "Foo") {
        console.log(x.some);
    }
});

Upvotes: 0

Itamar
Itamar

Reputation: 1634

You can use Array.some

This will return true if one is found.. The same callback as find can be used

const hasDetail = job.details.some(attr => {
  return attr.detail_name === 'Foo' });
        
if (hasDetail) {
  // todo process `some: "thing"` 
}

If you're simply want to get the value and then later on check if the property exists, you can use find and ?. operator

const addDetail = job.details.find(attr => {
  return attr.detail_name === 'Foo' });
        
if (addDetail?.detail_name === 'Foo') {
  // todo process `some: "thing"` 
}

Upvotes: 2

Related Questions