转换数据的最佳方式

Best way to transform data

我有一个供应商 API 在我的 nodejs 应用程序中调用 returns 各种对象,下面是 JSON 中一个对象的示例:

[{
"id": 365467865567,
"type": "PERSON",
"created_time": 1492809120,
"updated_time": 1492809542,
"last_contacted": 1492809128,
"properties": [
    {
    "type": "SYSTEM",
    "name": "phone",
    "value": "123456789"
    },
    {
    "type": "SYSTEM",
    "name": "first_name",
    "value": "Test2"
    },
    {
    "type": "SYSTEM",
    "name": "last_name",
    "value": "You"
    },
    {
    "type": "CUSTOM",
    "name": "utm_medium",
    "value": "email"
    }
]
}]

这种格式的数据不太好用,需要转成key,value格式。类似于:

[{
"id": 365467865567,
"type": "PERSON",
"created_time": 1492809120,
"updated_time": 1492809542,
"last_contacted": 1492809128,
"properties":
    {
    "phone": "123456789",
    "first_name": "Test2",
    "last_name": "You",
    "utm_medium": "email"
    }
}]

转换它的最有效方法是什么?

尝试遍历属性并重新分配变量。

var array = [{
  "id": 365467865567,
  "type": "PERSON",
  "created_time": 1492809120,
  "updated_time": 1492809542,
  "last_contacted": 1492809128,
  "properties": [{
    "type": "SYSTEM",
    "name": "phone",
    "value": "123456789"
  }, {
    "type": "SYSTEM",
    "name": "first_name",
    "value": "Test2"
  }, {
    "type": "SYSTEM",
    "name": "last_name",
    "value": "You"
  }, {
    "type": "CUSTOM",
    "name": "utm_medium",
    "value": "email"
  }]
}];

array.forEach(function(obj) {
  var properties = {};
  obj.properties.forEach(function(prop) {
    properties[prop.name] = prop.value;
  });
  obj.properties = properties;
});

https://jsfiddle.net/hycg5r80/3/

这里有一个方法,如果最有效但又短又好。

thing[0].properties = thing[0].properties.reduce( (p, n) => ( 
  n[p.name] = p.value;
  return n;
), {});