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

时间:2016-03-22 05:57:36

标签: javascript arrays underscore.js lodash

这是我的阵列:

[
    ['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
    }
}]

我如何得到这个?

3 个答案:

答案 0 :(得分:2)

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>

答案 1 :(得分:1)

你可以通过,

来做到
public class DatabaseGrabber extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selection_main);

    final TextView Shop_name = (TextView)findViewById(R.id.ShopName);

    DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
    databaseAccess.open();
    final List<String> ShopName = databaseAccess.getQuotes();
    databaseAccess.close();

    Button StartDraw = (Button)findViewById(R.id.draw_start);
    StartDraw.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collections.shuffle(ShopName);
            String random = ShopName.get(0);
            Shop_name.setText(random);
        }
    });
}
}

其中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的{​​{1}}。

答案 2 :(得分:0)

试试这个

&#13;
&#13;
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);
&#13;
&#13;
&#13;