将属性从字符串更新为JavaScript上的对象而不会发生突变

时间:2019-03-01 17:32:33

标签: javascript typescript immutability

遍历一个对象并更新它时,我觉得我做的不对。这是我构建的方法,我对record[header] = {label: record[header]};

表示怀疑

有人有更好的解决方案来避免对记录数组进行突变吗?

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 };
}

谢谢。

1 个答案:

答案 0 :(得分:2)

下面应该这样做。它使用新的对象传播运算符(...上的{})。就像Object.assign(),但语法更简洁。

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 };
}