繁体   English   中英

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

[英]Update a property from a string to object on JavaScript without mutation

当遍历一个对象并更新它时,我觉得我做的不对。 这是我构建的方法,我对record[header] = {label: record[header]};表示怀疑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 };
}

谢谢。

下面应该这样做。 它采用了全新的十岁上下的对象传播经营者( ...{} 就像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 };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM