mdixon18
mdixon18

Reputation: 1219

How to loop through an array and use the value to try and find an object name

I was writing to see if I can manipulate jquery arrays.

So I have an object:

myobject = {
   abc : {
      value      : 'abc',
      template   : '<div class="abc"></div>',
   },
},

Now what I have is another array that looks like this:

myarray = ["abc", "cde"];

So what I am trying to do is loop through myarray to see if it matches an object in the myobject.

Now I thought you would accomplish this by doing something like this:

for (var i = 0; i < myarray.length; i++) {
   if (myobject.myarray[i]) {
      // do something
   }
}

Now this gives me an error: Uncaught TypeError: Cannot read property '0' of undefined

So clearly this isn't the approach, how can I loop through myarray to see if myobject has an object that matches the name from the myarray array?

Upvotes: 0

Views: 76

Answers (5)

jessikwa
jessikwa

Reputation: 750

You were close with iterating through the array to look for the match, to finish use hasOwnProperty to check if the current place in the array matches any property in myobject

var myobject = {
    abc: {
        "value": "abc",
        "template": "test"
    }
}

var myarray = [ "abc", "cde" ];

for (var i = 0; i < myarray.length; i++) {
    var thisKey = myarray[i];
    if (myobject.hasOwnProperty(thisKey)) {
      //match found
    }
}

http://jsfiddle.net/jessikwa/obpacbao/3/

Upvotes: 0

ahmet2106
ahmet2106

Reputation: 5007

The problem within your code is, that myobject.myarray does not exists, so 0 of a non object is not available. Try to check with in:

for (var i = 0; i < myarray.length; i++) {
   if (myarray[i] in myobject) {
      // do something
   }
}

Upvotes: 2

codeberri
codeberri

Reputation: 21

You should be able to do the following.

for (var i = 0; i < myarray.length; i++) {
   if (myobject.hasOwnProperty(myarray[i])) {
      // do something
   }
}

Upvotes: 1

depperm
depperm

Reputation: 10746

You need to change the object reference from myobject.myarray[i] to myobject[myarray[i]]

var myobject = {
   'abc' : {
      value      : 'abc',
      template   : '<div class="abc"></div>',
   }
};


var myarray = ["abc", "cde"];


for (var i = 0; i < myarray.length; i++) {
   if (myobject[myarray[i]]!=undefined) {
      console.log(myobject[myarray[i]]);
   }
}

Upvotes: 1

Bobby Tables
Bobby Tables

Reputation: 3013

You can treat a javascript object la dictionary.

Documentation

myobject = {
    abc: {
        value: 'abc',
        template: '<div class="abc"></div>',
    },
},
myarray = ["abc", "cde"];
for (var i = 0; i < myarray.length; i++) {
    console.log(myobject[myarray[i]]);
}

Upvotes: 1

Related Questions