Here's a method I have written in an Ecma 6 component (Salesforce Lightning Web Components for anyone interested). I am sharing it here because this is more focused on JavaScript rather than LWC. Do you think this is the optimal approach to solve this issue?
I have two arrays, both containing objects:
My goal is to compare these arrays and create a new array of objects with a new property required: true
or required: false
. Is there a more efficient way to achieve this?
const RequiredFields =
[ { fieldApiName: 'FirstName', value: 'Test' }
, { fieldApiName: 'LastName', value: 'LastNameTest' }
]
const AllFields =
[ { fieldApiName: 'FirstName', value: 'Test' }
, { fieldApiName: 'LastName', value: 'LastNameTest' }
, { fieldApiName: 'Suffix', value: '' }
]
addRequiredFields(RequiredFields, Allfields) {
RequiredFields.forEach(field => {
field.required = true;
});
Allfields.forEach(field => {
var hasVal = Object.values(field).includes(true);
if (hasVal) {
console.log(field.fieldApiName + ' = TRUE');
} else {
field.required = false;
}
console.log(field);
});
return Allfields;
}
console.log ( addRequiredFields(RequiredFields, Allfields) )
output = [
{ fieldApiName: FirstName, value: 'Test' , required: true}
, { fieldApiName: LastName, value: 'LastNameTest' , required: true}
, { fieldApiName: Suffix, value: '', required: false }
]