Reputation: 935
I have a simple object with some simple arrays. I want to loop through each item in the object and check part of the array. For example, if a '0' or a '1' then do something.
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
}
I've tried the following but I get the entire object in each loop.
jQuery(formvalidation).each(function(){
//Gives the entire object.
console.log();
});
Upvotes: 0
Views: 54
Reputation: 935
Not to say that the previous answer here isn't right, but I thought Id go with what it led me to as the answer in this case.
jQuery.each(formvalidation, function(key, value){
if (value[1] == 0) {
e.preventDefault();
}
})
Upvotes: 1
Reputation: 61793
It's a bit unclear what kind of processing you're trying to do with each property (see my comment requesting clarification).
The example below demonstrates how to loop through each property and extract the first and second value from the arrays you're storing. This example is meant to illustrate how to access each property and its values only - you'll obviously need to plug your logic in where appropriate.
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
};
for (let prop in formvalidation) {
if (Object.prototype.hasOwnProperty.call(formvalidation, prop)) {
console.log(`Value of prop, ${prop}, is ${formvalidation[prop] [0]}:${formvalidation[prop][1]}`);
}
}
You could also use Object.keys
, which is a bit cleaner:
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
};
const keys = Object.keys(formvalidation)
for (const key of keys) {
console.log(formvalidation[key]);
}
Upvotes: 1