繁体   English   中英

Javascript 将数组索引简化为参数

[英]Javascript simplify array indexing as arguments

我有以下代码可以 100% 工作,但我不禁觉得它们是一种更好的方式或更简单的编写方式,也可能不是 😄all 并且总是感谢任何帮助👍🏼

const entity: any = response.organisation;

if (Array.isArray(responseKey)) {
  // responseKey e.g. ['site', 'accounts']
  // I feel this two declarations can be refactored
  const list = this.flattenGraphqlList<T>(entity[responseKey[0]][responseKey[1]]);
  const {totalCount} = entity[responseKey[0]][responseKey[1]];

  return {list, totalCount};
}

const list = this.flattenGraphqlList<T>(entity[responseKey]);
const {totalCount} = entity[responseKey];

return {list, totalCount};

不要做任何事情两次:

const entity: any = response.organisation;

const object = Array.isArray(responseKey) 
  ? entity[responseKey[0]][responseKey[1]] // responseKey e.g. ['site', 'accounts']
  : entity[responseKey];

const list = this.flattenGraphqlList<T>(object);
const {totalCount} = object;
return {list, totalCount};

我想你可以找到比object更具描述性的名称:-)

对于最后几行,我个人不希望使用解构,但这更像是一种风格选择:

return {
  list: this.flattenGraphqlList<T>(object),
  totalCount: object.totalCount
};

暂无
暂无

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

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