1

I'm trying to give the same behaviour to 4 values in my hash array.

For example:

var array = {};

  if (array[key].config.tmp == undefined) {
               array[key].config.tmp = {}
            }
            if(array[key].config.tmp.tp1){

            }
            if(array[key].config.tmp.tp2){

            }
            if(array[key].config.tmp.tp3){

            }
            if(array[key].config.tmp.tp4){

            }

Since tp1, tp2, tp3 and tp4 will have the same behaviour. I would like to simplify the validation.

Something like:

array[key].config.tmp.[tp1,tp2,tp3,tp4] is possible? Already tried. but it was

tp1,tp2,tp3 and tp4 may not exist(undefined). (tp1 and tp2 only sometimes).

Any advice so I won't duplicate code?

Thanks in advance

2 Answers 2

1

You could also use a filter on the array keys:

if ( ( array[key].config.tmp || {} ).keys().filter(
    function(k) { return /^tp[1234]/.test( k ) }
).length ) )
Sign up to request clarification or add additional context in comments.

Comments

1

use a short-circuit operator like ||. for instance, if you are checking for the existence of multiple properties, accessing a property which doesn't exist is falsy.

var c = a[key].config.tmp.a  || a[key].config.tmp.b || .... || //default

In this example, c will hold the value of the first of these to evaluate to true. You could also include a "Default" value at the end if they all return false. Keep in mind that accessing a property of a property that doesn't exist is a type error however, so you must be sure that at least config.tmp exists. So you can replace your code with

if (a[key].config.tmp.a  || a[key].config.tmp.b || ....) {

}

1 Comment

That will work for the first step of my validation, but I will have a problem after. Example: If tp1 is undefined and should exist I need to attribute 9999 and with that validation I can't identify which tp is (if it's tp1 or tp2 or tp3 or tp4)

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.