Objecy.keys()。map()与Array.map()

Marco -2 javascript arrays object javascript-objects

您能否给我一个论点,为什么方法A比方法B更好?

方法A:

const transformCompanyOptions = (companies: Array<{id: string, name: string}>, selectedId: string) => {
  return companies.map(key => {
    return {
      value: key.id,
      label: key.name,
      checked: key.id === selectedId
    }
  })
};

方法B:

const transformCompanyOptions = (companies: Array<{id: string, name: string}>, selectedId: string) => {
 const ret = Object.keys(companies).map((key) => {
    const newCompany = {};
    newCompany['value'] = companies[key].id;
    newCompany['label'] = companies[key].name;
    if (companies[key].id === selectedId) {
      newCompany['checked'] = true;
    }
    return newCompany;
  });
  return ret;
};

谢谢

StepUp.. 6

方法A是:

  • 短一点
  • 不太冗长
  • 清洁器
  • 具有更好的性能(您首先需要Object.keys在方法B中获得所有密钥)

另外,方法A可以改进:

const transformCompanyOptions = (companies: Array<{id: string, name: string}>, 
    selectedId: string) => {
  return companies.map(c => ({ 
      value: c.id,
      label: c.name,
      checked: c.id === selectedId
    }))
};

正如@TKoL在评论中所说:

尽量避免将参数.map作为关键调用,因为它实际上是公司本身,而不是key数组

  • 我也建议不要将.map中的参数称为key,因为它实际上是公司本身,而不是数组的键。 (3认同)