0

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?

mdixon18
  • 1,199
  • 4
  • 14
  • 35

5 Answers5

2

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
   }
}
ahmet2106
  • 4,957
  • 4
  • 27
  • 38
1

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]]);
}
Bobby Tables
  • 2,953
  • 7
  • 29
  • 53
1

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]]);
   }
}
depperm
  • 10,606
  • 4
  • 43
  • 67
1

You should be able to do the following.

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

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/

jessikwa
  • 750
  • 1
  • 8
  • 23