简体   繁体   中英

Convert object to array of objects in JavaScript

I have some data passed in via a query string and I've converted it to an object like:

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

I want to convert this to an array of objects like this:

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

What would be the best way to do this? Thanks!

Here's one way to do it

 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>'; 

You could do this with forEach loop and optional thisArg parameter

 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); 

You could use a hash table for reference and push the object to the Array, if a new hash is found.

 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); 

Just for the record, this can also be done directly as the result of a .reduce() method.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM