无法弄清楚如何使用所有匹配创建数组。我想我需要一个递归函数。
我想从下面的JSON中获取所有值,并创建一个包含所有值组合的数组。 可能有更多或更少的模型(Name4)和更多或更少的值。 有什么帮助吗?
var models = [
{
name: 'Name1',
values: [
'Title1Value1',
'Title1Value2',
'Title1Value3'
]
},
{
name: 'Name2',
values: [
'Title2Value1',
'Title2Value2'
]
},
{
name: 'Name3',
values: [
'Title3Value1',
'Title3Value2'
]
}
];
// Output array
var matches = [
[ 'Title1Value1', 'Title2Value1', 'Title3Value1' ],
[ 'Title1Value1', 'Title2Value1', 'Title3Value2' ],
[ 'Title1Value1', 'Title2Value2', 'Title3Value1' ],
[ 'Title1Value1', 'Title2Value2', 'Title3Value2' ],
[ 'Title2Value2', 'Title2Value1', 'Title3Value1' ],
[ 'Title1Value2', 'Title2Value1', 'Title3Value2' ],
[ 'Title1Value2', 'Title2Value2', 'Title3Value1' ],
[ 'Title1Value2', 'Title2Value2', 'Title3Value2' ],
[ 'Title1Value3', 'Title2Value1', 'Title3Value1' ],
[ 'Title1Value3', 'Title2Value1', 'Title3Value2' ],
[ 'Title1Value3', 'Title2Value2', 'Title3Value1' ],
[ 'Title1Value3', 'Title2Value2', 'Title3Value2' ]
];
答案 0 :(得分:0)
var indices = [];
var lengths = [];
for (i = 0; i<models.length; i++) {
indices[i] = 0;
lengths[i] = models[i].values.length;
}
var matches = [];
while (indices[0] < lengths[0]) {
var row = [];
for (i = 0; i<indices.length; i++) {
row.push(models[i].values[indices[i]]);
}
matches.push(row);
/* Cycle the indexes */
for (j = indices.length-1; j >= 0; j--) {
indices[j]++;
if (indices[j] >= lengths[j] && j != 0) {
indices[j] = 0;
} else {
break;
}
}
}