对于相互嵌套的循环

时间:2018-09-07 15:29:23

标签: javascript

我正在尝试编写一个脚本,该脚本将为我返回某些参数的所有可能组合。这是我目前拥有的。问题是,tagLoop列表的长度可以更改,然后在最嵌套的循环中需要另一个for循环。然后又一个又一个。我正在添加带有用于循环的变量的屏幕截图。

编辑:添加了工作片段

 var tagsLoop = ["mobile_size", "desktop_size", "tag_test"]
 var bigArray = [{tag: "mobile_size", key: "size", val: "6"},
    {tag: "mobile_size", key: "size", val: "2"},
    {tag: "desktop_size", key: "size", val: "10"},
    {tag: "desktop_size", key: "size", val: "20"},
    {tag: "tag_test", key: "oracle", val: ""},
    {tag: "tag_test", key: "pros", val: ""}]

        for (var i = 0; i < bigArray.length; i++) {
            if (bigArray[i]['tag'] == tagsLoop[0]) {
                var part1 = bigArray[i]['key'] + '=' + bigArray[i]['val']

                for (var j = 0; j < bigArray.length; j++) {
                    if (bigArray[j]['tag'] == tagsLoop[1]) {
                        var part2 = "&" + bigArray[j]['key'] + '=' + bigArray[j]['val']

                        for (var k = 0; k < bigArray.length; k++) {

                            if (bigArray[k]['tag'] == tagsLoop[2]) {


                                var part3 = "&" + bigArray[k]['key'] + '=' + bigArray[k]['val']


                                console.log(part1, part2, part3)
                            }
                        }
                    }
                }
            }
        }

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以首先获取分组数据,并使用所需项及其值的组合来构建新数组。

function getCartesian(array, keys) {
    var temp = array.reduce((r, { tag, key, val }) => {
            (r[tag] = r[tag] || []).push([key, val].join('='));
            return r;
        }, Object.create(null));

    return keys
        .map(k => temp[k])
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
        .map(a => a.join('&'));
}

var array = [{ tag: "mobile_size", key: "size", val: "6" }, { tag: "mobile_size", key: "size", val: "2" }, { tag: "desktop_size", key: "size", val: "10" }, { tag: "desktop_size", key: "size", val: "20" }, { tag: "tag_test", key: "oracle", val: "" }, { tag: "tag_test", key: "pros", val: "" }],
    tags = ["mobile_size", "desktop_size", "tag_test"],
    result = getCartesian(array, tags);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }