Check propery of an objects array

Check property of an objects array

If you have an array of objects and you want to check the value of a specific property for all the objects in the array, you can use a loop to iterate over each object and access its property.

Example:


const fruits = [
  { name: "Apple", color: "Red" },
  { name: "Orange", color: "Orange" },
  { name: "Banana", color: "Yellow" }
];

// Loop through the array of objects
for (let i = 0; i < fruits.length; i++) {
  // Access the property of each object
  console.log(fruits[i].color);
}

In this example, we have an array of fruit objects and we want to check the value of the color property for each fruit. We use a for loop to iterate over the array and access the color property of each fruit object using dot notation.

You can also use the forEach() method to iterate over the array:

Example:


const fruits = [
  { name: "Apple", color: "Red" },
  { name: "Orange", color: "Orange" },
  { name: "Banana", color: "Yellow" }
];

// Use forEach() to loop through the array of objects
fruits.forEach(function(fruit) {
  // Access the property of each object
  console.log(fruit.color);
});

In this example, we use the forEach() method to iterate over the array and access the color property of each fruit object using dot notation inside the callback function.

You can also use map() or filter() methods to check the values of specific properties in an array of objects.

Using map() method, you can create a new array that contains only the values of the property you want to check:

Example:


const fruits = [
  { name: "Apple", color: "Red" },
  { name: "Orange", color: "Orange" },
  { name: "Banana", color: "Yellow" }
];

// Use map() to create a new array of the color property values
const colors = fruits.map(function(fruit) {
  return fruit.color;
});

console.log(colors);

In this example, we use the map() method to create a new array that contains only the color property values of each fruit object. The callback function returns the value of the color property for each fruit object.

Using filter() method, you can create a new array that contains only the objects with a specific property value:

Example:


const fruits = [
  { name: "Apple", color: "Red" },
  { name: "Orange", color: "Orange" },
  { name: "Banana", color: "Yellow" }
];

// Use filter() to create a new array of objects with the color property value of "Red"
const redFruits = fruits.filter(function(fruit) {
  return fruit.color === "Red";
});

console.log(redFruits);

In this example, we use the filter() method to create a new array that contains only the objects with the color property value of "Red". The callback function returns true for objects with the color property value of "Red" and false for all other objects.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe