I'm trying to avoid to write the number of lines since the response is same for all the fields so I tried to use for loop with categorizing the fields['mandatory', 'optional'] but still I need to write twice time for loop. Is this possible to write more efficiently without compromising the performance in one go.
//mandatory
obj.required['test1' number] = true;
obj.visible['test1' number] = true;
obj.required['test2' number] = true;
obj.visible['test2' number] = true;
obj.required['test3' number] = true;
obj.visible['test3' number] = true;
//optional
obj.visible['test4' number] = true;
obj.visible['test5' number] = true;
Tried with for loop:
var mandatoryField = ['test1', 'test2', 'test3'];
var optionalField = ['test4', 'test5'];
for(var i=0; i<mandatoryField.length; i ) {
obj.required[madatoryField[i] number] = true;
obj.visible[madatoryField[i] number] = true;
}
CodePudding user response:
Can you change the structure of the fields?
const obj = {
visible: {
test1: false,
test2: false,
test3: false,
test4: false,
test5: false,
test6: false,
test7: false,
test8: false,
},
required: {
test1: false,
test2: false,
test3: false,
test4: false,
test5: false,
test6: false,
test7: false,
test8: false,
},
};
const fields = [
{ field: 'test1', required: true },
{ field: 'test2', required: true },
{ field: 'test3', required: true },
{ field: 'test4' },
{ field: 'test5' },
];
fields.forEach(({ field, required }) => {
const key = field; // `${field}${number}`;
obj.visible[key] = true;
if (required) {
obj.required[key] = true;
}
});
console.log(obj);
CodePudding user response:
Something like this wll help you to achieve this in one iteration.
var mandatoryField = ['test1', 'test2', 'test3'];
var optionalField = ['test4', 'test5'];
const limit = new Array(Math.max(mandatoryField.length, optionalField.length)).fill(0);
limit.forEach((item, index) => {
if(mandatoryField[index]) {
obj.required[mandatoryField[index] number] = true;
obj.visible[mandatoryField[index] number] = true;
}
if(optionalField[index]) {
obj.visible[optionalField[index] number] = true;
}
})