JavaScript : How to find data in an array objects.

To find objects in an array that have a specific value for the docNo property, you can use the filter() method. Here’s an example code snippet that filters the data array to find all objects that have a docNo value of "doc123":

const data = [
  {
    "id": 1,
    "docNo": "doc123",
  },
  {
    "id": 2,
    "docNo": "doc456",
  },
  {
    "id": 3,
    "docNo": "doc123",
  }
];

const doc123Objects = data.filter(obj => obj.docNo === "doc123");

console.log(doc123Objects); // Output: [ { "id": 1, "docNo": "doc123", ... }, { "id": 3, "docNo": "doc123", ... } ]

In this example, the filter() method is called on the data array and returns a new array that contains only the objects with a docNo property of "doc123". The filtered array is assigned to the doc123Objects variable and then logged to the console.

If you only want to find the first object that has a docNo value of "doc123", you can use the find() method instead of filter(). For example:

const doc123Object = data.find(obj => obj.docNo === "doc123");

console.log(doc123Object); // Output: { "id": 1, "docNo": "doc123", ... }

Leave a Reply

Your email address will not be published. Required fields are marked *