如何将此数组转换为对象数组?

How to convert this array to an array of objects?

这是我的数组:

[
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['F', "_180"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4]
    ['F', "_360"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['m', 5]
    ['F', "_480"],
]

这就是我想要实现的:

[{
    profile_180: {
        x: 1,
        y: 2,
        z: 3
    }
}, {
    profile_360: {
        x: 1,
        y: 2,
        z: 3,
        t: 4
    }
}, {
    profile_480: {
        x: 1,
        y: 2,
        z: 3
        t: 4,
        m: 5
    }
}]

我如何得到这个?

data = [
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['F', "_180"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['F', "_360"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['m', 5],
    ['F', "_480"],
];

var result = {};
var current = {};
data.forEach(function(row) {
  if (row[0] == 'F') {
    result['profile' + row[1]] = current;
    current = {};
  } else {
    current[row[0]] = row[1];
  }
});
console.log(result);
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

你可以做到,

var res = [], tmp = {}, obj = {};
x.forEach(function(itm,i) {
 if(itm[0] !== "F"){
  tmp[itm[0]] = itm[1];
 } else {
   obj["profile_" + itm[1]] = tmp;
   res.push(obj);
   tmp = {}, obj ={};
 }
});

其中 x 是包含 dataarray

试试这个

var obj = [
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['F', "_180"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['F', "_360"],
    ['x', 1],
    ['y', 2],
    ['z', 3],
    ['t', 4],
    ['m', 5],
    ['F', "_480"],
];
var output = [];
var tmpArr = {};
obj.forEach(function(value,index){

   console.log(value);
   if (value[0] != 'F' )
   {
      tmpArr[value[0]] = value[1];
   }
   else
   {
     var profileValue = "Profile_" + value[1];
     var tmpObj = {};
     tmpObj[profileValue] = tmpArr;
      output.push( tmpObj );
      tmpArr = {};
   }
});
document.body.innerHTML += JSON.stringify(output,0,4);