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?

2

5 Answers 5

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
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like this, as it's easy to log if there isn't ever a match. Thanks
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]]);
}

Comments

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]]);
   }
}

Comments

1

You should be able to do the following.

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.