在JavaScript中将对象转换为对象数组

时间:2016-08-07 16:56:05

标签: javascript jquery

我通过查询字符串传递了一些数据,并将其转换为以下对象:

{
  "Person1_Age": 22,
  "Person1_Height": 170,
  "Person1_Weight": 72,
  "Person2_Age": 27,
  "Person2_Height": 160,
  "Person2_Weight": 56,
}

我想将其转换为这样的对象数组:

[
  {
    "name": "Person1",
    "age": "22",
    "height": 170,
    "weight": 72
  },
  {
    "name": "Person2",
    "age": "27",
    "height": 160,
    "weight": 56
  }
]

最好的方法是什么?谢谢!

4 个答案:

答案 0 :(得分:0)

这是一种方法

var obj = {
  "Person1_Age": 22,
  "Person1_Height": 170,
  "Person1_Weight": 72,
  "Person2_Age": 27,
  "Person2_Height": 160,
  "Person2_Weight": 56,
}

var map = {}, arr = [];

Object.keys(obj).forEach(function(k) {
  var parts = k.split('_'),
      key   = parts.shift().toLowerCase(),
      val   = parts.pop().toLowerCase();

  if (!(key in map)) map[key] = {};
  map[key][val] = obj[k];
});

for (var k in map) {
  map[k].name = k;
  arr.push(map[k]);
}

document.body.innerHTML = '<pre>' + JSON.stringify(arr, 0, 4) + '</pre>';

答案 1 :(得分:0)

您可以使用forEach循环和可选的thisArg参数

执行此操作

var data = {
  "Person1_Age": 22,
  "Person1_Height": 170,
  "Person1_Weight": 72,
  "Person2_Age": 27,
  "Person2_Height": 160,
  "Person2_Weight": 56,
}

var result = [];
Object.keys(data).forEach(function(e) {
  var part = e.split('_');
  var person = part[0];
  var p = part[1].toLowerCase();

  if(!this[person]) {
    this[person] = {name: person}
    result.push(this[person]);
  } 
  
  this[person][p] = data[e];
}, {})

console.log(result);

答案 2 :(得分:0)

如果找到新的哈希,您可以使用哈希表进行引用并将对象推送到数组。

&#13;
&#13;
var obj = { Person1_Age: 22, Person1_Height: 170, Person1_Weight: 72, Person2_Age: 27, Person2_Height: 160, Person2_Weight: 56 },
    arr = [];

Object.keys(obj).forEach(function(k) {
    var parts = k.split('_');

    if (!this[parts[0]]) {
        this[parts[0]] = { name: parts[0] };
        arr.push(this[parts[0]]);
    }
    this[parts[0]][parts[1].toLowerCase()] = obj[k];
}, Object.create(null));

console.log(arr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

仅作为记录,这也可以作为.reduce()方法的结果直接完成。

var list = {
  "Person1_Age": 22,
  "Person1_Height": 170,
  "Person1_Weight": 72,
  "Person2_Age": 27,
  "Person2_Height": 160,
  "Person2_Weight": 56
};

var res = Object.keys(list).reduce(function(a, b) {
  var m = b.match(/Person(\d+)_(.+)/);
  (a[m[1] - 1] = a[m[1] - 1] || {name: 'Person' + m[1]})[m[2].toLowerCase()] = list[b];
  return a;
}, []);

console.log(res);