Madasu K Madasu K - 12 days ago 5
Javascript Question

angularjs, need to transform object properties

In my angularjs application I have model which is array of objects as shown below:

$scope.originalData = [{

"id": 10000,
"transactionid": "gec43434",
"status": "COMPLETED",
"session_id": "TTYUU455667",
"errors": "1",
"start_timestamp": "2016-11-07 02:35:35",
"log_field": "Sample Text For Testing"

}, {

"id": 10001,
"transactionid": "r34fdfdf",
"status": "COMPLETED",
"session_id": "dfdfer3453df",
"errors": "3",
"start_timestamp": "2016-10-07 03:20:15",
"log_field": "Sample Text2 For Testing"

}];


Now I need to modify the same array of objects to appear as shown below, except
log_field
remaining all properties should go under another property of the same object.

$scope.modifiedData = [{
"subItems": {
"id": 1000,
"transactionid": "gec43434",
"status": "COMPLETED",
"session_id": "TTYUU455667",
"errors": "1",
"start_timestamp": "2016-11-07 02:35:35"
},
"log_field": "Sample Text For Testing"

}, {
"subItems": {
"id": 10001,
"transactionid": "r34fdfdf",
"status": "COMPLETED",
"session_id": "dfdfer3453df",
"errors": "3",
"start_timestamp": "2016-10-07 03:20:15"
},
"log_field": "Sample Text2 For Testing"

}]

Answer

Here is what you could do. using Array.map and delete.

var originalData = [{
  "id": 10000,
  "transactionid": "gec43434",
  "status": "COMPLETED",
  "session_id": "TTYUU455667",
  "errors": "1",
  "start_timestamp": "2016-11-07 02:35:35",
  "log_field": "Sample Text For Testing"
}, {
  "id": 10001,
  "transactionid": "r34fdfdf",
  "status": "COMPLETED",
  "session_id": "dfdfer3453df",
  "errors": "3",
  "start_timestamp": "2016-10-07 03:20:15",
  "log_field": "Sample Text2 For Testing"
}];


var result = originalData.map((item) => {
  var log_field = item.log_field;
  delete item.log_field;
  return {
    "subItems": item,
    "log_field": log_field
  };
});

console.log(result);

In case,If you shouldn't modify the original data, here is what you could do.

var originalData = [{
  "id": 10000,
  "transactionid": "gec43434",
  "status": "COMPLETED",
  "session_id": "TTYUU455667",
  "errors": "1",
  "start_timestamp": "2016-11-07 02:35:35",
  "log_field": "Sample Text For Testing"
}, {
  "id": 10001,
  "transactionid": "r34fdfdf",
  "status": "COMPLETED",
  "session_id": "dfdfer3453df",
  "errors": "3",
  "start_timestamp": "2016-10-07 03:20:15",
  "log_field": "Sample Text2 For Testing"
}];


var result = originalData.map((item) => {
  //Withou modifying original data.
  var resultItem = Object.assign({}, item),
    log_field = resultItem.log_field;
  delete resultItem.log_field;

  return {
    "subItems": resultItem,
    "log_field": log_field
  };
});
console.log(originalData);
console.log(result);

Comments