0

I want to declare and assign default values to variables

let country, state, fruits;
let checkBoxfields = ['country', 'state', 'fruits'];
checkBoxfields.forEach(field=>{
    if(some condition){
        return field = true;
    }else{
        field = false;
    }

I want final output as such

country = true;
state = false;
fruits = true;
1
  • Can you add more information about what problem you are having implementing this? Commented Oct 30, 2019 at 22:39

2 Answers 2

3

You can create an empty object and then iterate over the checkBoxFields and then populate the object as needed

const obj = {};

const checkBoxfields = ['country', 'state', 'fruits'];
checkBoxfields.forEach(field => {
    if (some condition) {
        obj[field] = true;
    } else {
        obj[field] = false;
    }
});

Sample output

console.log(obj); // {country: false, state: true, fruits: true}
Sign up to request clarification or add additional context in comments.

5 Comments

I don't want object, I want a direct variable with value
Are these variable declared in global scope ? @RohitHannurkar
Yes the declaration is in global scope
You can take out the variables by using const {country, state, fruits} = obj
Yes I will go with this answer, thwnk you @Abito
2

If the structure is consistent and value are always in the same order, then you can map and destructure value in variable with desired name something like this

let checkBoxfields = ['country', 'state', 'fruits'];
let [country, state, fruits] = checkBoxfields.map(field => {
  return field === 'country' || field === 'fruits'
})

console.log(country, state, fruits)


If the variables are defined in global scope you can use window to reference variable, That being said you should avoid using global as much as possible it has it's own drawback, makes code so hard to debug

var country, state, fruits;
const checkBoxfields = ['country', 'state', 'fruits'];
checkBoxfields.forEach(field => {
  if (field === 'country' || field === 'fruits') {
    window[field] = true;
  } else {
    window[field] = false;
  }
});


console.log(country,state,fruits)

3 Comments

No! The structure may change, based on the condition
@RohitHannurkar the other answer is pretty much what you need in that condition
Thank you @CodeManiac for the Answer, I will be going with Abito answer, considering the variables are not declared in global scope as you rightly said it has its own drawback and hard to debug

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.