Search code examples
javascripttypescriptimmutability

Update a property from a string to object on JavaScript without mutation


When iterating through an object and updating it I feel that I am not doing it right. This is the method I have built to do it and I have doubts about record[header] = {label: record[header]};

Does anybody have a better solution to avoid mutation records array?

setAfterRecords(preview: any): void {
    const { columns: headers } = preview;
    const { rows: records } = preview;

    records.map((record, i) => {
        headers.forEach(header => {
            record[header] = {
                label: record[header],
            };
        });

        return record;
    });

    this.after = { headers, records };
}

Thank you.


Solution

  • The following should do it. It uses the new-ish object spread operator (... on {}). It's like Object.assign() but in a more concise syntax.

    setAfterRecords(preview: any): void {
      const { columns: headers, rows: records } = preview;
    
      // Build a new array of records.
      const newRecords = records.map(record => {
    
        // Build a new record object, adding in each header.
        return headers.reduce((c, header) => {
    
          // This operation shallow-copies record from the initial value or
          // previous operation, adding in the header.
          return { ...c, [header]: { label: record[header] } }
        }, record)
      })
    
      this.after = { headers, records: newRecords };
    }