When working with NetSuite SuiteScript, you may need to set multiple field values on a record efficiently. Instead of calling setValue repeatedly, you can streamline your code by storing the field-value pairs in an object and iterating through them using a for loop.
A common way to set multiple field values on a record looks like this:
newRecord.setValue({ fieldId: ‘custbody_field_1’, value: 1 });
newRecord.setValue({ fieldId: ‘custbody_field_2’, value: 2 });
newRecord.setValue({ fieldId: ‘custbody_field_3’, value: 3 });
newRecord.setValue({ fieldId: ‘custbody_field_4’, value: 4 });
newRecord.setValue({ fieldId: ‘custbody_field_5’, value: 5 });
newRecord.setValue({ fieldId: ‘custbody_field_6’, value: 6 });
newRecord.setValue({ fieldId: ‘custbody_field_7’, value: 7 });
While this works, it is not scalable. If you have a large number of fields, updating them one by one makes your code longer, harder to maintain, and prone to errors.
A cleaner and more efficient way is to store the field-value pairs in an object and iterate over it using a for...in loop.
Refactored Code:
const fieldValues = {
custbody_field_1: 1,
custbody_field_2: 2,
custbody_field_3: 3,
custbody_field_4: 4,
custbody_field_5: 5,
custbody_field_6: 6,
custbody_field_7: 7
};
for (let fieldId in fieldValues) {
newRecord.setValue({ fieldId: fieldId, value: fieldValues[fieldId] });
}
Why This Approach is Better?
✅ Code Readability – Instead of repeating setValue, the logic is neatly structured.
✅ Easy Maintenance – If you need to add or remove a field, you simply update the fieldValues object.
✅ Scalability – Works well even when dealing with dozens of fields.
Using an object to store field values and a loop to set them in a NetSuite record enhances efficiency and maintainability. Whether you’re working with Sales Orders, Invoices, or Estimates, this method keeps your scripts organized and flexible.