如何正确格式化此对象

时间:2017-04-11 10:50:17

标签: javascript node.js html5 forms object

我有一个带有数组的对象,它提供了这个输出(输入来自一系列带有组名的表单):

{ 
  username: [ 'username1', 'username2' ],
  firstname: [ 'firstname1', 'firstname2' ],
  lastname: [ 'lastname1', 'lastname2' ],
  email: [ 'email1', 'email2' ],
 }

我希望对象的格式如下:

  [{username : username1,
    firstname : firstname1,
    lastname : lastname1,
    email : email1},

    {username: username2,
     firstname: firstname2,
     lastname : lastname2,
     email : email2}
                       ]

当我使用node.js时,我认为有一些方法可以使用lodash。谁能给我一些帮助?谢谢!

3 个答案:

答案 0 :(得分:1)

可能的解决方案,使用Array#forEachObject.keys



var obj = { username: [ 'username1', 'username2' ], firstname: [ 'firstname1', 'firstname2' ], lastname: [ 'lastname1', 'lastname2' ], email: [ 'email1', 'email2' ] }, res = [];
 
    obj.username.forEach(function(_, i) {
      var object = {};
      Object.keys(obj).forEach(function(c) {
        object[c] = obj[c][i];
      });
      res.push(object);
    });

    console.log(res);




Array#reduce选项。



var obj = { username: [ 'username1', 'username2' ], firstname: [ 'firstname1', 'firstname2' ], lastname: [ 'lastname1', 'lastname2' ], email: [ 'email1', 'email2' ] },
 
    res = obj.username.reduce(function(s,a,i) {
      var object = {};
      Object.keys(obj).forEach(function(c) {
        object[c] = obj[c][i];
      });
      s.push(object);
      return s;
    }, []);

    console.log(res);




答案 1 :(得分:1)

简单的javascript:

var oldObj = { 
  username: [ 'username1', 'username2' ],
  firstname: [ 'firstname1', 'firstname2' ],
  lastname: [ 'lastname1', 'lastname2' ],
  email: [ 'email1', 'email2' ],
};
var newArray =[];
for(var key in oldObj)
{
  oldObj[key].forEach(function(property){
    var index = oldObj[key].indexOf(property);
    if(!newArray[index])
    newArray[index] = {};
    newArray[index][key] = property
  });
}

答案 2 :(得分:0)

使用lodash -

console.log(_.transform(myObj, function(result, value, key) {
  _.each(value, function( val, i){
        if(!result[i]) result[i] = {};
            result[i][key]= val;
        });
}, []));

在此处试试 - lodash unwind