0

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(); 

});
2
  • Can you clarify what you mean by "loop through each item in the object"? If you are looping through each property, how will you know what to check? Are you going to execute the same checking/logic on title that you want to execute on video? Commented Feb 11, 2020 at 14:47
  • To loop through title, categories, price etc and check to see if the array had a value of 1 or 0. Commented Feb 12, 2020 at 10:37

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Good solution. I'm a huge fan of jQuery, but I didn't provide an example in this case simply because jQuery adds absolutely no value here. +1 anyway for those who are looking for a jQuery solution.

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.