How to Find an Object Key Value Inside an Array

Hi, does anyone know how to find an object key value inside an array? For instance, if I have an array of objects called records.

var records = [{

id: 12345

type: transaction

}]

If I want to check this array to see if there’s an object that contains the ID “12345”, how would I do that? Is there a way without looping through the whole array? I know I can use the array.includes method to find a value inside a regular array. But that doesn’t seem to work because I’m looking for an object key value inside an array.

Beginner Asked on October 31, 2019 in SuiteScript.
Add Comment
2 Answer(s)

No, I do not believe there is any more ‘native’ way of doing this.
I would just do something like the following:

function findId(id, records) {
    for (var i = 0; i < records.length; i++) {
      if (records[i].id === id) {
        return true;
      }
    }
}

Decent article with more generalized function:
https://www.linkedin.com/pulse/javascript-find-object-array-based-objects-property-rafael

Intermediate Answered on October 31, 2019.

Ok, thanks! That’s basically what I ended up doing too. I was just seeing if there was some method that does this that I was unaware of.

on October 31, 2019.

If you are using SuiteScript 2.1 and have access to the ES6 array functions in this post, you could use these as well:
https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects

on October 31, 2019.

Gotcha. Thanks!

on October 31, 2019.
Add Comment

Also, if you load the lodash library in, you can use the _.find function. In general, that whole library can be very useful.

Beginner Answered on October 31, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.
  • This site made possible by our sponsors:   Tipalti   Celigo   Limebox   Become a Sponsor