将对象项与循环配对

时间:2013-09-20 06:02:30

标签: javascript jquery

我有以下数据,我想知道如何以这种格式的电子邮件:密码匹配email1到password1和email2到password2。如果我执行object[0] +":"+ object[1]object[2] +":"+ object[3],我可以这样做但是当对象被10个或更多项填充时,此方法效率不高。我怎么能用循环呢?

我正在使用以下代码创建结构:

$("#accounts").on("submit", function(event) {
    event.preventDefault();
    var form = $(this).serializeArray();
});

enter image description here

3 个答案:

答案 0 :(得分:2)

您可以更改for循环中的增量。尝试:

var results = [];
For(var i = 0; i < vals.length; i += 2) {
    results.push( { vals[i].value: vals[i+1].value });
}

答案 1 :(得分:0)

//
Array.prototype.e = Array.prototype.forEach;
function pair( arr ) {
    var len = arr.length;
    if ( len ) {
        do {
            arr.push( arr.splice( 0, 2 ) );
        } while ( ( len -= 2 ) >= 2 );
    }
    return arr;
};
var yourData = [
                { name:"email1", value:"321" },
                { name:"pw1",    value:"123" },
                { name:"email2", value:"qwe" },
                { name:"pw2",    value:"ewq" },
                { name:"email3", value:"234" },
                { name:"pw3",    value:"432" }
               ],
    pairs    = {};
pair( yourData )
.e(
    function ( P ) {
        pairs[ P[0].name ] = P[1].name;
    }
);
console.log( pairs );
// Object { email1="pw1", email2="pw2", email3="pw4"}
//

答案 2 :(得分:0)

您可以尝试增加循环步骤。

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FStatements#for_Statement

代码:

var testMe=new Array({"name":"em1"},{"pwd":"pwd1"},{"name":"em2"},{"pwd":"em2"});
console.log(testMe)
for (var i = 0; i < testMe.length; i+=2) {
  console.log(testMe[i].name+"-->"+testMe[i+1].pwd)
}

演示:http://jsfiddle.net/IrvinDominin/qbVwH/