Henry Wartemberg
Henry Wartemberg

Reputation: 21

Iterating through JS Array + Array Properties

I'm a bit of a novice I was hoping someone could point out what I am doing wrong.

The idea is for searchArray to loop through array values &properties. It takes the arguments (property, value). When I call the function I get a RefernencError saying that property(hostname) is undefined. Is there something wrong with browsingHistory[i].property?

function searchArray(property, value) {
    for (i = 0; i < browsingHistory.length; i++) {
        return value === browsingHistory[i].property;
    }
}

Upvotes: 0

Views: 56

Answers (2)

Hazarapet Tunanyan
Hazarapet Tunanyan

Reputation: 2865

If you using a variable as a property of any object, you can use with "." syntax.You have to use it as array with that property (like array indexes).For example

var property = "name";
....
anyObject[property] // equals to anyObject['name'] or anyObject.name

Upvotes: 0

Apolo
Apolo

Reputation: 4050

browsingHistory[i].property means the value of the property called "property".

use browsingHistory[i][property] instead


Demo

function searchArray(property, value) {
    for (i = 0; i < my_array.length; i++) {
        return value === my_array[i][property];
    }
}


var my_array = [
  {
    x: "foo",
    y: "bar"
  },
  {
    x: "foooooo",
    y: "baaaaar"
  }
]


// should output "true" because my array contains an element with a 
// property named "x" and which value is "foo"
document.body.innerHTML = searchArray("x","foo");

Upvotes: 3

Related Questions