0

I want to pass a property acessor or object literal 'key' as an argument in a function so I can use it with dot notation in a for loop.

For example:

let myArray = [
{
apples: 4,
bananas: 1,
},
{
apples: 10,
bananas: 2,
},
{
apples: 4,
bananas: 3,
},
]

Array.prototype.count = function(objProperty, testValue) {
  var count = 0;
  for (var i = 0; i < this.length; ++i) {
    if (this[i].objProperty === testValue) {
      count++;
    }
  }
  return count
}

console.log(myArray.count('apples', 4)) // expect: 2
console.log(myArray.count('apples', 10)) // expect: 1
Gallaxhar
  • 976
  • 1
  • 15
  • 28

1 Answers1

3

You can access an object's property like Object.property or Objects[property] (in case, property is a string datatype)

let myArray = [
{
apples: 4,
bananas: 1,
},
{
apples: 10,
bananas: 2,
},
{
apples: 4,
bananas: 3,
},
]

Array.prototype.count = function(arrayProperty, testValue) {
  var count = 0;
  for (var i = 0; i < this.length; ++i) {
    if (this[i][arrayProperty] === testValue) {
      count++;
    }
  }
  return count
}

console.log(myArray.count('apples', 4)) // expect: 2
console.log(myArray.count('apples', 10)) // expect: 1