Javascript 简化数组索引作为参数
Javascript simplify array indexing as arguments
我有以下代码可以 100% 工作,但我不禁觉得他们是一种更好的或更简单的编写方法,或者可能不是全部,我们将不胜感激任何帮助
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
};
我有以下代码可以 100% 工作,但我不禁觉得他们是一种更好的或更简单的编写方法,或者可能不是全部,我们将不胜感激任何帮助
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
};