我正在尝试创建一个对象数组,其中包含代表由三个字符串数组提供的组合可能性的每种情况的对象。我的对象数组(集合)中的每个对象都应包含属性 {format: '', iconType: '', state: ''}
其中每个属性可以是字符串或空值。
所以在我的代码中我有 3 个字符串数组...就像这样:
const buttonFormats = ['compact', 'regular', 'fluid'];
const stateParams = [
null,
'secondary',
'2',
'tertiary',
'3',
'warning',
'!',
'danger',
'!!!',
'danger-secondary',
'2!!!',
'primary-line',
'1l',
'secondary-line',
'2l',
'tertiary-line',
'3l',
'warning-line',
'!l',
'danger-line',
'!!!l'
];
const iconTypes = [null, 'add', 'edit'];
const allCombinations = [];
我的计划是建立三个嵌套循环,其中我们获取一个循环的当前值并将其与其他循环的值组合起来,就像这样......
public makeButtonStates(): any[] {
const buttonFormats = ['compact', 'regular', 'fluid'];
const stateParams = [
null,
'secondary',
'2',
'tertiary',
'3',
'warning',
'!',
'danger',
'!!!',
'danger-secondary',
'2!!!',
'primary-line',
'1l',
'secondary-line',
'2l',
'tertiary-line',
'3l',
'warning-line',
'!l',
'danger-line',
'!!!l'
];
const iconTypes = [null, 'add', 'edit']; // these are the available icons
const allCombinations = [];
buttonFormats.forEach((format) => {
const currentCombinaton: any = {};
currentCombinaton.format = format;
iconTypes.forEach((icon) => {
currentCombinaton.iconType = icon;
stateParams.forEach((state) => {
currentCombinaton.state = state;
console.log(currentCombinaton);
allCombinations.push(currentCombinaton);
});
});
});
return allCombinations;
}
public ngOnInit(): void {
this.buttonStates = this.makeButtonStates();
console.log(this.buttonStates);
}
当我使用 console.log()
输出时,这不起作用当前写入控制台的值组合是我所期望的,但是当我编写嵌套循环函数的结果时, this.buttonStates
的值或allCombinations
对象数组中的所有对象都具有相同的 iconType 和 state 属性值,这些是字符串数组中的最后一次 ´{iconType: "edit", state: "!!!l"}` 此屏幕截图开发者控制台给出了输出的想法...
显然我的实现是错误的,我应该使用 .map
或.filter
或.reduce
相反,为什么我的输出数组只采用 stateParams 和 iconType 数组的最后一个值?
如果您能帮助我发现这一点,非常感谢。
最佳答案
如果没有嵌套循环,您可以对值采用组合算法并稍后应用对象结构。
const
buttonFormats = ['compact', 'regular', 'fluid'],
iconTypes = [null, 'add', 'edit'],
stateParams = [ null, 'secondary', '2', 'tertiary', '3', 'warning', '!', 'danger', '!!!', 'danger-secondary', '2!!!', 'primary-line', '1l', 'secondary-line', '2l', 'tertiary-line', '3l', 'warning-line', '!l', 'danger-line', '!!!l'],
result = [buttonFormats, iconTypes, stateParams]
.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
.map(([format, iconType, state]) => ({ format, iconType, state }));
console.log(result.length);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 使用 javascript/typescript 创建一个对象数组,使其具有 3 个数组的所有可能性组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53630911/