Search code examples
javascriptnode.jsapivendor

Best way to transform data


I have a vendor API call in my nodejs app that returns various objects, with the below being an example of one object in the the 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"
    }
]
}]

Its not very easy to use the data in this format, and need to transpose it to a key,value format. Something similar to:

[{
"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"
    }
}]

What would be the most efficient way to transform this?


Solution

  • Try looping over the properties and reassigning the variable.

    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/