0

无法弄清楚如何创建一个包含所有匹配项的数组。我想我需要一个递归函数。

我喜欢从下面的 JSON 中获取所有值,并创建一个包含所有值组合的数组。可能有更多或更少的模型(名称4)和更多或更少的值。有什么帮助吗?

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' ]
];
4

1 回答 1

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;
        }
    }
}
于 2012-12-06T11:18:24.513 回答